如何在数组中找到多个峰值?
给定数组:[1,2,3,4,5,4,3,2,3,4,5,6,5,4,3,2,4,2]
我可以用下面的代码找到最大峰值。

func findPeakElement(_ readings: [Int]) -> Int {
   if readings.count == 0 {
      return 0
   }

   while left < right {
      middle1 = (left + right) / 2
      middle2 = middle1 + 1
      if readings[middle1] < readings[middle2] {
         left = middle2
      } else {
         right = middle1
      }
   }
   return left
}

但是,我需要找到所有的峰;[5,6,4]
我需要什么代码?即使它只告诉我峰值的数目(3)也足够了。

最佳答案

可以迭代元素并检查值是升序还是降序,并将元素与最后一个元素进行比较。如果当前元素大于最后一个元素,则将其标记为升序。如果该值较小且为升序,则将其标记为降序并附加最后一个元素:

func findPeakElement(_ readings: [Int]) -> [Int] {
    var ascending = false
    var peaks: [Int] = []
    if var last = readings.first {
        readings.dropFirst().forEach {
            if last < $0 {
                ascending = true
            }
            if $0 < last && ascending  {
                ascending = false
                peaks.append(last)
            }
            last = $0
        }
    }
    return peaks
}

let readings = [1,2,3,4,5,4,3,2,3,4,5,6,5,4,3,2,4,2]
let peaks = findPeakElement(readings)
print(peaks)   // [5, 6, 4]

09-07 02:32