IDEA#
- If a problem requries time complexity, It’s binary serach.
SOLUTION/CODE#
- Compare
nums[mid]andnums[mid+1]- If
nums[mid]is less thannums[mid + 1], it means there must be a peak on the right side. - Else, it means that might be a peak on left side. (
midcan be a peak itself)
- If
class Solution {
public int findPeakElement(int[] nums) {
int l =0, r=nums.length-1, mid=0;
while (l < r){
mid = (l+r)/2;
if(nums[mid] < nums[mid+1]){
l = mid+1;
}else{
r = mid;
}
}
return l;
}
}