Skip to content

Latest commit

 

History

History
33 lines (27 loc) · 657 Bytes

寻找峰值.md

File metadata and controls

33 lines (27 loc) · 657 Bytes

https://leetcode-cn.com/problems/find-peak-element

代码

function  findPeakElement(nums) {
  let n = nums.length
  let l = 0
  let r = n - 1
  function is_target(i) {
    if (i == 0)  return nums[i] > nums[1]
    if (i == n - 1) return nums[i] > nums[n - 2]
    return nums[i] > nums[i - 1] && nums[i] > nums[i + 1]
  }
  while (l < r) {
    mid = (l + r) >> 1
    if (is_target(mid)) return mid
    if (nums[mid] > nums[mid + 1]) {
      r = mid - 1
    } else {
      l = mid + 1
    }      
  }
  return l
}

复杂度分析

时间复杂度:$O(logN)$ 空间复杂度:$O(1)$