【问题标题】:Finding surrounding elements of value in Array在 Array 中查找周围的值元素
【发布时间】:2021-01-14 02:02:54
【问题描述】:

我有一个 CGFloat 数组。我还有一个任意值 a,它可以是任何 CGFloat。我的问题是,我如何有效地找到 a 位于哪两个索引之间。附带说明,a 永远不会低于或大于数组的最小值或最大值,因此无需担心。

举个简单的例子,我可能有:

let array: [CGFloat] = [4, 7, 10, 22, 23, 25, 67]

// a can be any random number, this initialization is for the example
let a = 14

// some algorithm that calculates indexes
// code returns index 2 and 3 (or it returns items 10, 22)

我开发了一种涉及 for 循环的方法,但是,列表越大,代码效率越低。有没有更智能、更高效的代码?

感谢大家的帮助:)

【问题讨论】:

  • 输入数组排序了吗?
  • 一个可能的解决方案,firstIndex(where:),你会发现第一个索引值大于你的值(你得到上限)。然后,较低的索引,即该索引减 1。
  • 给定a == 10,应该返回什么?
  • 请您自己努力解决这个问题。

标签: arrays swift for-loop indexing


【解决方案1】:

您要查找的内容称为中间二分搜索。这种方法有很多例子Example #2。请注意,如果您传递的值低于第一个值,它将返回起始索引,而高于最后一个值的值将返回最后一个索引。

extension Collection where Element: Comparable, Index == Int {
    func binarySearch(_ element: Element) -> Index {
        var low = 0
        var high = count - 1
        while low < high {
            let mid = low + ((high - low + 1) / 2)
            let current = self[mid]
            if current == element {
                return mid
            } else if current < element {
                low = mid
            } else {
                high = mid - 1
            }
        }
        return low
    }
}

let array: [CGFloat] = [4, 7, 10, 22, 23, 25, 67]
let a = 14
let indexA = array.binarySearch(CGFloat(a))  // 2
let indexB = indexA + 1                      // 3

【讨论】:

    【解决方案2】:

    如果您的数组始终是有序的,请使用:

    let array: [CGFloat] = [4, 7, 10, 22, 23, 25, 67]
    let a: CGFloat = 14
    if let maxIndex = array.firstIndex(where: { $0 > a }), maxIndex > 0 {
        print("a between \(maxIndex - 1) and \(maxIndex) indexes")
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多