Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- One observation:arr[i] can't be same as arr[i-1] && arr[i+1] for all possible i.see constraints.
- Why binary search working?
- One thing for sure,If an array doesn't contain a peek then it must be strictly increasing or decreasing
- that is not possible here because nums[-1] and nums[n] is INT_MIN so there is definitely a peek there.
- case 1: If arr[mid-1]<arr[mid] && arr[mid+1]<arr[mid] then return mid;
- case 2: If arr[mid-1]>arr[mid] then arr[-1] is also smaller than arr[mid-1] then there must be some peek
- in arr[-1] to arr[m1]
- case 3: vice versa
- so go in the direction of side which is having greater element than arr[mid]
- '''
- class Solution:
- def findPeakElement(self, arr: List[int]) -> int:
- l,r=0,len(arr)-1
- while l<=r:
- mid=(l+r)//2
- print(l,r,mid)
- if (mid-1<0 or arr[mid]>arr[mid-1]) and (mid+1>=len(arr) or arr[mid]>arr[mid+1]):
- return mid
- elif (mid-1>=0 and arr[mid-1]>arr[mid]): ###no Corner case handling here, must move in the larger neighordirection
- r=mid-1
- else:
- l=mid+1
- return l
Advertisement
Add Comment
Please, Sign In to add comment