Advertisement
imashutosh51

Find peak element

Oct 16th, 2022 (edited)
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. /*
  2. One observation:arr[i] can't be same as arr[i-1] && arr[i+1] for all possible i.see constraints.
  3. Why binary search working?
  4. One thing for sure,If an array doesn't contain a peek then it must be strictly increasing or decreasing
  5. that is not possible here because nums[-1] and nums[n] is INT_MIN so there is definitely a peek there.
  6.  
  7. case 1: If arr[mid-1]<arr[mid] && arr[mid+1]<arr[mid] then return mid;
  8. case 2: If arr[mid-1]>arr[mid] then arr[-1] is also smaller than arr[mid-1] then there must be some peek
  9.         in arr[-1] to arr[m1]
  10. case 3: vice versa
  11. so go in the direction of side which is having greater element than arr[mid]
  12. */
  13.  
  14. class Solution {
  15. public:
  16.     int findPeakElement(vector<int>& nums) {
  17.         if(nums.size()==1) return 0;
  18.         int i=0,j=nums.size()-1;
  19.         int n=nums.size();
  20.         while(i<j){
  21.             int mid=(i+j)/2;
  22.             if((mid==0 || nums[mid-1]<nums[mid]) && (mid==n || nums[mid+1]<nums[mid])) return mid;
  23.             if(nums[mid+1]>nums[mid]) i=mid+1;
  24.             else j=mid-1;
  25.         }
  26.         return i;
  27.     }
  28. };
  29.  
  30. #Python
  31. class Solution:
  32.     def findPeakElement(self, nums: List[int]) -> int:
  33.         if len(nums)==1:
  34.             return 0
  35.         l,r=0,len(nums)-1
  36.         while l<r:
  37.             mid=(l+r)//2
  38.             print(mid)
  39.             if (mid==0 or nums[mid-1]<nums[mid]) and (mid==len(nums) or nums[mid]>nums[mid+1]):
  40.                 return mid
  41.             elif mid>0 and nums[mid-1]>nums[mid]:
  42.                 r=mid-1
  43.             elif mid<len(nums):
  44.                 l=mid+1
  45.         return l
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement