[Leetcode 162] Find Peak Element (Medium)

Solution

  1. 题目只要求求一个peak即可,那么用二分法可以根据 nums [middle] & nums [middle + 1]的值的比较,来判断,峰值可能出现在middle的左边还是右边
    • 如果if (nums[middle] < nums[middle + 1]),那么峰值可能出现的范围就是[middle + 1, end]
    • 如果if (nums[middle] > nums[middle + 1]),那么峰值可能出现的范围就是[start, middle]
  2. 不断通过二分法调整startend,直到base case: start + 1 == end. 得到峰值。
class Solution {
    public int findPeakElement(int[] nums) {
        if (nums == null || nums.length == 0)
            return Integer.MIN_VALUE;
        
        int start = 0;
        int end = nums.length - 1;
        
        while (start + 1 < end) {
            int middle = start + (end - start) / 2;
            
            // search in the right hand side
            if (nums[middle] < nums[middle + 1]) {
                start = middle + 1;
            } else {
                end = middle;
            }
        }
        
        return nums [start] > nums [end] ? start : end;
    }
}

你可能感兴趣的:([Leetcode 162] Find Peak Element (Medium))