Easy Java Solution using BS


  • 0
    D
    public class Solution {
        public int findPeakElement(int[] nums) {
            int len = nums.length;
            if (len == 1) return 0;
            int start = 0;
            int end = len -1;
            int res = 0;
            if (nums[start]>nums[start+1]) return 0; // according to nums[-1] = nums[n] = -∞, 
            if (nums[end]>nums[end-1]) return end;// so return start or end if one of them is greater than its neighbor.
            while (start<end) {  
                int mid = (start + end)/2;
                if (nums[mid]>nums[mid+1] && nums[mid]>nums[mid-1]) { //mid is greater than its neighbors
                    res = mid;
                    break;
                }else if (nums[mid]<nums[mid+1]) {
                    start = mid;
                }else {
                    end = mid;
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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