[LeetCode]Find Peak Element

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.spa

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

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

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

分析

这种找Peak Element的首先想到的是binary search, 由于有更优的时间复杂度,不然brute force O(n)的方法太直接了。input

binary search的方法就是比较当前element与邻居,至于左邻居仍是右邻居均可以,只要一致就行。不断缩小范围,最后锁定peak element.it

这种相似题也有不少Follow up, 好比先增后减的数组怎么找指定元素,甚至先增后减再增的数组怎么找指定元素。io

方法都是同样的,就是先得找到peak element的点,而后根据peak点将整个数组分红几部分,对于每一个部分来讲,是单调的,因此能够对每一个部分分别用binary search来找元素。function

复杂度

time: O(logn), space: O(1)class

代码

public class Solution {
    public int findPeakElement(int[] nums) {
        int l = 0;
        int r = nums.length - 1;
        while (l < r) {
            int mid = l + (r - l) / 2;
            if (nums[mid] < nums[mid + 1]) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        return l;
    }
}
相关文章
相关标签/搜索