Share my 10-line java code with comments


  • 0
    M
    public class Solution {
        public int findPeakElement(int[] nums) {
            if (nums==null || nums.length==0) { return -1; }
            int left = 0, right = nums.length-1;
            while (left < right-1) {
                int mid = left + (right-left)/2;
                if (nums[mid]>nums[mid+1] && (mid-1<0 || mid-1>=0&&nums[mid]>nums[mid-1])) {  // nums[mid]>its left and right neighbors. note that here mid+1<nums.length always holds.
                    return mid;
                } else if (mid-1>=0 && nums[mid-1]>nums[mid]) { right = mid; }  // left neighbor is larger, search left
                else { left = mid; }
            }
            return nums[left] > nums[right] ? left : right;
        }
    }

Log in to reply
 

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