Clean Java O(logn) using Binary Search


  • 0
    public int findPeakElement(int[] nums) {
            int n = nums.length;
            if (n == 1) return 0;
            int left = 0;
            int right = n-1;
            
            while (left <= right){
                int mid = left + (right - left)/2;
                int numLeft = (mid == 0)? Integer.MIN_VALUE:nums[mid-1];
                int numRight = (mid == n-1)? Integer.MIN_VALUE:nums[mid+1];
                
                if ((mid == 0 && nums[mid]> numRight) || (mid == n-1 && nums[mid] > numLeft))
                    return mid;
                    
                if (nums[mid] > numLeft && nums[mid] > numRight)
                    return mid;
                else if (nums[mid] < numRight)
                        left = mid+1;
                    else
                        right = mid - 1;
            }
            
            return -1;
        }
    

Log in to reply
 

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