easy to understand java solution with comment


  • 0
    L
    public class Solution {
        public int findPeakElement(int[] nums) {
            if(nums.length == 1) return 0;
            if(nums[0] > nums[1]) return 0;
            if(nums[nums.length-2] < nums[nums.length-1]) return nums.length-1;
            
            int start = 1;
            int end = nums.length-2;
            int mid;
            
            while(start+1 < end) {
                mid = start + (end-start)/2;
                
                //total 4 situation
                
                if(nums[mid-1] < nums[mid] && nums[mid] > nums[mid+1]) return mid;
                
                if(nums[mid-1] < nums[mid] && nums[mid] < nums[mid+1]) start = mid;
                
                //Can combine the last two scenarioes, since always discard the right part when mid is minimum.
                
                else if(nums[mid-1] > nums[mid] && nums[mid] > nums[mid+1]) end = mid; 
                else if(nums[mid-1] > nums[mid] && nums[mid] < nums[mid+1]) end = mid;
            }
            if(nums[start] == nums[end]) return start;//this is for the number of element is only 3.
            if(nums[start] > nums[end]) return start;
            if(nums[start] < nums[end]) return end;
            return -1;
        }
    }
    

Log in to reply
 

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