Skip to main content
  1. Posts/

LeetCode-162 寻找峰值

·1 min·

LeetCode-162 寻找峰值 #

Solution 1 #

二分. 如果 $nums[i] < nums[i + 1]$ , 可以证明右半边存在峰值, 反之同理.

代码如下:

class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        nums = [-inf] + nums + [-inf]
        l, r = 1, len(nums) - 2
        while l <= r:
            mid = (l + r) // 2
            if nums[mid] > nums[mid - 1] and nums[mid] > nums[mid + 1]:
                return mid - 1
            if nums[mid] < nums[mid + 1]:
                l = mid + 1
            else:
                r = mid - 1
        return mid - 1