[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;
    }
}
相關文章
相關標籤/搜索