104. Find Peak Element
Medium
Binary Search on Answer
Binary Search
Problem
A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, return the index of any peak element. You may imagine nums[-1] = nums[n] = -infinity.
Examples
Example 1
Input: [1,2,3,1]
Output: 2
3 is greater than both adjacent values.
Example 2
Input: [1,2,1,3,5,6,4]
Output: 5
Constraints
� 1 <= nums.length <= 1000
� -2^31 <= nums[i] <= 2^31 - 1
� nums[i] != nums[i + 1] for every valid i
Hints
?? Compare the middle element with its right neighbor.
?? If nums[mid] < nums[mid + 1], a peak exists on the right side.
?? Otherwise, a peak exists on the left side including mid.
Expected Complexity
Time: O(log n)
Space: O(1)
Follow-up
Can you solve it in O(log n) time?
Practice Notes
Attempts: 0
Time spent: 0min
Hints used: 0
JavaScript
00:00
Loading...
Case 1
Case 2
Case 3
Input
[1,2,3,1]Expected
2