Easy java solution with comments


  • 0
    O

    The recommended solution should run in log(n) time, so it seems pretty intuitive to use some kind of binary search.
    See comments in code below for details.

      public class Solution {
        public int findPeakElement(int[] nums) {
            if(nums == null || nums.length < 1) return 0;
            int low = 0;
            int high = nums.length - 1;
            int mid = (low + high) / 2;
            while(low < high) {
                // This means the candidate peak can be between low and mid
                // mid itself is included since it is also possible to be a peak
                if(nums[mid] > nums[mid + 1]) {
                    high = mid;
                } else {
                // This means the candidate peak can be between mid and high
                // where mid itself is excluded since it is smaller than mid + 1
                    low = mid + 1;
                }
                mid = (low + high) / 2;
            }
            return mid;
        }
    }

Log in to reply
 

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