arrays - 在 Swift 中快速查找数组中的最小值

标签 arrays swift

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/

相关文章:

ios - 无法在 Swift 2.2 的同一行上声明 NSManaged 变量

ios - SwiftUI : API URL fetch failed

ios - CollectionView 组合布局中的部分标题 z 索引 - iOS 13

java - 复制数组的值

javascript - 递归地将数组元素放入自己的数组中

ios - 更改导航 Controller 项目颜色

swift - 在 Apples Swift 3 beta 6 中使用 withMemoryRebound

java - 从字节数组中读取图片

c++ - 当我在函数参数中使用指针时遇到错误

javascript - 修改对象数组中的对象值