Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

mid和左右相比,每次舍去一半(logn的精髓:每次舍去一半,可以是有一半一定有解,或者是有一半一定没解)。

  1. 如果mid比左右都大,返回mid
  2. 如果mid小于左边,左边一定有峰值,舍去右边
  3. 如果mid小于右边,右边一定有峰值,舍去左边。注意同时小于左右两边的话,取任何一边都可以
  4. 注意mid在边界时的情况,不要再拿它和左右比较
  5. 如果一直没返回,最后返回start和end大的那个

Code

public class Solution {
    public int findPeakElement(int[] nums) {
        //或者可以写成start=1, end=nums.length-2,这样中间不用判断mid
        int start = 0, end = nums.length-1;
        while (start + 1 < end){
            int mid = start + (end - start)/2;
            if (mid==0 || mid==nums.length-1 || (nums[mid]>nums[mid-1] && nums[mid]>nums[mid+1])) return mid;
            else if (nums[mid] < nums[mid-1]) end = mid; 
            else if (nums[mid] < nums[mid+1]) start = mid;
        }

        if (nums[start] > nums[end]) return start;
        else return end;
    }
}