Use binary search. If nums[mid] < nums[mid + 1], a peak must exist in the right half; otherwise a peak exists in the left half.
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
# Compare mid with next element
if nums[mid] < nums[mid + 1]:
# We are on an upward slope.
# Peak must be on the right.
left = mid + 1
else:
# We are on a downward slope.
# Peak could be mid or on the left.
right = mid
return left
class Solution {
public int findPeakElement(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = (left + right) / 2;
// Compare mid with next element
if (nums[mid] < nums[mid + 1]) {
// We are on an upward slope.
// Peak must be on the right.
left = mid + 1;
} else {
// We are on a downward slope.
// Peak could be mid or on the left.
right = mid;
}
}
return left;
}
}