let numbers = [1, 6, 3, 9, 4, 6]
let min = minElement(numbers) // 1
let position = find(array, min)!
有没有更好的方法来查找次要元素在数组中的位置?循环搜索,在这种情况下它是最快的。
min = Int.max
for (index,value) in enumerate(array){
if value < min{
min = value
position = index
}
}
最佳答案
如果您喜欢“功能性”方式:
let array = [6, 3, 1, 9, 4, 6]
let (position, min) = reduce(enumerate(array), (-1, Int.max)) {
$0.1 < $1.1 ? $0 : $1
}
position // -> 2
min // -> 1
但我不知道它比 for
循环更快:)
关于arrays - 在 Swift 中快速查找数组中的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29274840/