Medium
042Find Peak Element
Return the index of any peak element. A peak is strictly greater than its neighbors.
EXAMPLES
Example 1
Input
{
"nums": [
1,
2,
3,
1
]
}
Output
2FUNCTION SHAPE
nums: intArray→intSOLUTION NOTE
Ternary search converted to binary search. Compare adjacent elements to determine which half contains a peak. Check nums[mid-1] <= nums[mid] creates monotone TTTFFF pattern.
Reveal reference solution +
pythonREFERENCE
def findPeakElement(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = ceil(left + (right - left) / 2)
if nums[mid - 1] <= nums[mid]:
left = mid
else:
right = mid - 1
return leftTime
O(log n)Space
O(1)