162. Find Peak Element - cocoder39/coco39_LC GitHub Wiki
this is a special scenario to apply binary search. Though the input is not sorted, it still works because it could reduce the search space by half each iteration
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
n = len(nums)
#if n == 1:
# return 0
low, high = 0, n-1
while low + 1 < high:
mid = low + (high - low) // 2 # low+1 <= mid <= high-1
if nums[mid-1] < nums[mid] > nums[mid+1]:
return mid
elif nums[mid] < nums[mid-1]: # from -1 to mid-1 to mid: up then down, so mid-1 is peak or there is peak between (-1, mid-1)
high = mid
else: # nums[mid] < nums[mid+1]: # from mid to mid+1 to n: up then down, so mid+1 is peak or there is peak between (mid+1, n)
low = mid
if nums[low] < nums[high]:
# if (low < 1 or nums[low-1] < nums[low]) and (low+1 >= n or nums[low] > nums[low+1]):
return high
return low
========================================================================
since nums[-1] and nums[n] are -INF. the trend of the sequence must be going up then going down.
-
if (nums[mid] > nums[mid - 1])
, sincenums[mid - 1] < nums[mid] > nums[n]
, the trend within[mid - 1, n]
must be going up then going down, there exists a peek -
if (nums[mid] < nums[mid - 1])
, sincenums[-1] < nums[mid - 1] > nums[mid]
, the trend within[-1, mid]
must be going up then going down, there exists a peek
tip: it is safe to access nums[mid - 1]
since mid - 1 >= start
as we have discussed in Binary search (bug)
int findPeakElement(vector<int>& nums) {
int start = 0, end = nums.size() - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) {
return mid;
}
//nums[mid - 1] < nums[mid] > nums[n], there exists a peek within [mid, n - 1]
else if (nums[mid] > nums[mid - 1]) { //mid - 1 >= start is valid
start = mid;
}
//nums[-1] < nums[mid - 1] > nums[mid], there exists a peek within [0, mid - 1]
else { //nums[mid] < nums[mid - 1]
//a peek is within [-1, mid]
end = mid;
}
}
if(nums[start] >= nums[end]){
return start;
}
return end;
}