Find Peak Element

With , find an index let and . Note that for any , . A linear solution is simple, but we can solve this problem in . Make use of the conditions that , we take a iteration way that is very similar to binary search. For an index , we search peak element in the left side of it if , conversely, we search peak element in the right side.

To prove this algorithm is simple. If , as each adjoined element is different, there must be a that let , so there must be a peek element in the range of . There are a similar conclusion if and in the right side.

public class FindPeakElement {

    public int findPeakElement(int[] nums) {
        int l = 0;
        int r = nums.length - 1;
        int mid;

        while(true) {
            mid = (l + r) / 2;
            if (mid - 1 >= 0 && nums[mid - 1] > nums[mid]) {
                r = mid - 1;
            } else if (mid + 1 < nums.length && nums[mid + 1] > nums[mid]) {
                l = mid + 1;
            } else {
                return mid;
            }
        }
    }
}