Find Peak Element

题目链接:https://leetcode.com/problems...

这道题给了条件:nums[i] != nums[i+1],然后两端是负无穷。所以能用binary search做。因为只要知道当前点是递增的,只要往右边找肯定能找到peak,大不了到最后,因为nums[n-1]是永远小于当前点的。左边同理。

public class Solution {
    public int findPeakElement(int[] nums) {
        // binary search
        int l = 0, r = nums.length - 1;
        while(l + 1 < r) {
            int mid = l + (r - l) / 2;
            // increase
            if(mid == 0 || nums[mid] > nums[mid - 1]) l = mid;
            // decrease
            else r = mid;
        }
        if((l == 0 || nums[l-1] < nums[l]) && (l == nums.length - 1 || nums[l] > nums[l+1])) return l;
        return r;
    }
}

lulouch13
13 声望6 粉丝

下一篇 »
Flip Game II