查找峰值元素(多个)SWIFT

时间:2018-01-13 00:47:17

标签: arrays swift search element

如何在阵列中找到多个峰值?

给出阵列:[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)就足够了。

2 个答案:

答案 0 :(得分:1)

假设您想要任何值在其两侧具有较低值的值,您可以执行以下操作:

func findPeaks(readings: [Int]) -> [Int] {
    var result = [Int]()
    if readings.count >= 3 {
        for i in 1..<readings.count-1 {
            if readings[i - 1] < readings[i] && readings[i + 1] < readings[i] {
                result.append(readings[i])
            }
        }
    }

    return result
}

let readings = [1,2,3,4,5,4,3,2,3,4,5,6,5,4,3,2,4,2]
print(findPeaks(readings: readings))

输出:

  

[5,6,4]

一个不能按原样处理的案例如下:

[1,4,4,1]

此算法无法找到4。支持这一点需要更多的工作。

答案 1 :(得分:0)

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

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]