Find nearest smaller number in array

前端 未结 2 1632
孤街浪徒
孤街浪徒 2020-12-12 04:22

I would like to be able to find the nearest smaller value in an array of numbers. For instance, if I have:

[1, 4, 6, 9, 14, 39]

And I\'m lo

相关标签:
2条回答
  • 2020-12-12 04:49

    Given that the array is sorted , You need

    if let value = numbers.last(where: { $0 <= target }) {
      print(value)
    }
    
    0 讨论(0)
  • 2020-12-12 04:58

    This is a generic solution using binary search. The array must be sorted

    extension RandomAccessCollection where Element : Comparable {
        func lowerElement(of value: Element) -> Element? {
            var slice : SubSequence = self[...]
    
            while !slice.isEmpty {
                let middle = slice.index(slice.startIndex, offsetBy: slice.count / 2)
                if value < slice[middle] {
                    slice = slice[..<middle]
                } else {
                    slice = slice[index(after: middle)...]
                }
            }
            return slice.startIndex == self.startIndex ? nil : self[self.index(before: slice.startIndex)]
        }
    }
    
    let array = [1, 4, 6, 9, 14, 39]
    let result = array.lowerElement(of: 8)
    print(result)
    
    0 讨论(0)
提交回复
热议问题