[Med] 162. Find Peak Element

2019-10-25  本文已影响0人  Mree111

Description

A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that nums[-1] = nums[n] = -∞.

Solution

class Solution:
    def findPeakElement(self, A: List[int]) -> int:
        start, end = 0, len(A) - 1
        while start + 1 <  end:
            mid = (start + end) // 2
            if A[mid] < A[mid - 1]:
                end = mid
            elif A[mid] < A[mid + 1]:
                start = mid
            else:
                end = mid
        if A[start] < A[end]:
            return end
        else:
            return start
上一篇 下一篇

猜你喜欢

热点阅读