852. 山脉数组的峰顶索引

https://leetcode-cn.com/problems/peak-index-in-a-mountain-array/

解法一:

水题,从前往后遍历找第一个下降点即可。

class Solution:
    def peakIndexInMountainArray(self, A: List[int]) -> int:
        n = len(A)
        i = 0
        while i+1 < n and A[i] < A[i+1]:
            i += 1
        return i

解法二:二分

class Solution:
    def peakIndexInMountainArray(self, arr) -> int:
        n = len(arr)
        l = 0
        r = n - 1
        while l <= r:
            mid = l + (r - l) // 2
            #找山顶,则遇到上坡就右移,遇到下坡就左移
            if arr[mid - 1] < arr[mid] < arr[mid + 1]:
                l = mid + 1
            elif arr[mid - 1] > arr[mid] > arr[mid + 1]:
                r = mid - 1
            else:
                return mid
        return l

最后更新于