swift - 数组范围内的最小值

标签 swift

我有一个价格列表,想找到不包括第一个元素的最低价格(这是 HackerRank 上另一个问题的子集)。

我的版本太慢,超时了。我怀疑这是由于我的 ArraySlice。

这是我的(工作)代码:

func calculateMins(prices: [Int]) {
    for j in 1..<prices.count  {
        let lowestPreviousPrice = prices[1...j].min()!
        print (lowestPreviousPrice)
    }
}

calculateMins(prices: [4,8,2,4,3])

是否有性能更好的版本,也许是不使用 ArraySlice 的版本?

最佳答案

只需使用dropFirst() 函数。

var array = [1,8,2,4,3]
var array2 = array.dropFirst() // Returns a subsequence containing all but the first element of the sequence.
array2.min() // 2

关于swift - 数组范围内的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54418028/

相关文章:

ios - Subspec vendored_frameworks 作为另一个 cocoapod 库

ios - 跳过 nil 值并继续执行其余代码

ios - 在 Swift xCode 中将 UI 导航栏设置为半透明

ios - Xcode 8 Objective-C 类别警告

ios - 将自动布局与 UIImageView 一起使用不会保留帧大小

ios - 在 Swift 的 AVPlayerViewController 中播放来自 Youtube 的视频

ios - iOS 界面生成器的等高约束问题

ios - SceneKit - 修改节点面向方向的速度

ios - 当我在我的应用程序中按下按钮时,我将如何打开谷歌地图?

ios - 重复符号 Apple Mach-O 链接器错误