DEV Community

Alysa
Alysa

Posted on • Updated on

Find Peak Element | LeetCode | Java

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading πŸ₯°
Feel free to comment ✍️
Follow for more 🀝 && Happy Coding πŸš€

If you enjoy my content, support me by following me on my other socials😍:
Github
Hashnode
Medium
Twitter(X)

Top comments (0)