Easy to understand Java Solution.. plus video


  • 0
    T
    public class Solution {
        public int findPeakElement(int[] nums) {
            if (nums == null && nums.length == 0) {
                return -1;
            }
            if (nums.length == 0) {
                return 0;
            }
            int start = 0;
            int end = nums.length -1;
            while (start + 1 < end) {
                int mid = (start + end) / 2;
                if (isPeak(nums, mid)) {
                    return mid;
                } else if (nums[mid-1] > nums[mid]) {
                    end = mid;
                } else {
                    start = mid;
                }
            }
            if (isPeak(nums, start)) {
                return start;
            }
            if (isPeak(nums, end)) {
                return end;
            }
            return -1;
            
        }
        public boolean isPeak (int[] nums, int k) {
            if (k == 0 && nums.length == 1) { //only 1 element
                return true;
            }
            if (k == 0 && nums.length > 1) { //left boundary
                return (nums[0] > nums[1]);
            }
            if (k == nums.length-1 && nums.length > 1) { //right boundary
                return nums[k] > nums[k-1];
            }
            if (nums[k] > nums[k-1] && nums[k] > nums[k+1]) {
                return true;
            }
            return false;
        }
    }
    

    Found a helpful video on youtube..https://www.youtube.com/watch?v=a7D77DdhlFc
    explains everything.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.