問題: git
方法: 最簡單的方法,循環遍歷一遍,可是算法複雜度是O(n)。題目提示覆雜度是O(logN),能夠很容易地聯想到二分,若是中點前面的值大於中點的值,則前面的區間必存在峯值,反以後面必存在,經過二分查找能夠更高效地找到峯值。github
具體實現:算法
class FindPeakElement {
fun findPeakElement(nums: IntArray): Int {
return findPeakElement(nums, 0, nums.lastIndex)
}
private fun findPeakElement(nums: IntArray, startIndex: Int, endIndex: Int): Int {
val midIndex = (endIndex + startIndex) / 2
val midVal = nums[midIndex]
val leftIndex = midIndex - 1
val leftVal = when (midIndex) {
0 -> Long.MIN_VALUE
else -> nums[leftIndex].toLong()
}
val rightIndex = midIndex + 1
val rightVal = when (midIndex) {
nums.lastIndex -> Long.MIN_VALUE
else -> nums[rightIndex].toLong()
}
return if (midVal > leftVal && midVal > rightVal) {
midIndex
} else if (midVal < leftVal) {
findPeakElement(nums, startIndex, leftIndex)
} else {
findPeakElement(nums, rightIndex, endIndex)
}
}
}
fun main(args: Array<String>) {
val input = intArrayOf(1, 2, 4, 2)
val findPeakElement = FindPeakElement()
println(findPeakElement.findPeakElement(input))
}
複製代碼
有問題隨時溝通bash