A peak element is an element that is strictly greater than its neighbors.
The nature of the input will be "It will be in an increasing fashion but suddenly will start to decrease at some point. That point will be pivot point".
We need to find that Pivot Point. One thing is for sure that it kinda involves sorted array.
Whenever the array is sorted, it will always involve "Binary Search".
class Solution {
public int findPeakElement(int[] nums) {
int n = nums.length;
if(n==1)
return 0;
int low = 0, high = n-1;
while(low<high){
int mid = low + (high-low)/2;
if(mid>low && mid<high && nums[mid-1]<nums[mid] && nums[mid]>nums[mid+1])
return mid;
else if(nums[mid]<nums[mid+1])
low = mid+1;
else
high = mid-1;
}
return low;
}
}
Thanks for reading🥰.
Feel free to comment🖌️ and like the post💓
Follow for more 🤝 && Happy Coding🚀👩💻
Don't forget to check-out my other socials😍:
Github
Hashnode
Medium
Twitter(X)
What's your thoughts?
Please Register or Login to your account to be able to submit your comment.