Advertisement
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 {
- public:
- int findPeakElement(vector<int>& nums) {
- if(nums.size()==1) return 0;
- int i=0,j=nums.size()-1;
- int n=nums.size();
- while(i<j){
- int mid=(i+j)/2;
- if((mid==0 || nums[mid-1]<nums[mid]) && (mid==n || nums[mid+1]<nums[mid])) return mid;
- if(nums[mid+1]>nums[mid]) i=mid+1;
- else j=mid-1;
- }
- return i;
- }
- };
- #Python
- class Solution:
- def findPeakElement(self, nums: List[int]) -> int:
- if len(nums)==1:
- return 0
- l,r=0,len(nums)-1
- while l<r:
- mid=(l+r)//2
- print(mid)
- if (mid==0 or nums[mid-1]<nums[mid]) and (mid==len(nums) or nums[mid]>nums[mid+1]):
- return mid
- elif mid>0 and nums[mid-1]>nums[mid]:
- r=mid-1
- elif mid<len(nums):
- l=mid+1
- return l
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement