美文网首页
[Med] 162. Find Peak Element

[Med] 162. Find Peak Element

作者: Mree111 | 来源:发表于2019-10-25 00:18 被阅读0次

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

相关文章

网友评论

      本文标题:[Med] 162. Find Peak Element

      本文链接:https://www.haomeiwen.com/subject/tqrjvctx.html