玩命加载中 . . .

162-寻找峰值


LeetCode 162. Find Peak Element

LeetCode-162

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

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

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

You must write an algorithm that runs in $O(logn)$ time.

示例 1:

输入:nums = [1,2,3,1]
输出:2
解释:3 是峰值元素,你的函数应该返回其索引 2

示例 2:
输入:nums = [1,2,1,3,5,6,4]
输出:15 
解释:你的函数可以返回索引 1,其峰值元素为 2;
     或者返回索引 5, 其峰值元素为 6

method: 二分模板一

如果midmid+1大,说明峰值在左边,所以r=mid
如果midmid+1小,说明峰值在右边,所以l=mid+1

考虑边界条件,l指向倒数第二个元素,r指向最后一个元素,midl
如果满足条件,则r = mid = l,退出,结果正确
如果不满足,则l = mid + 1 = r,退出,结果也正确

int findPeakElement(vector<int>& nums) {
    int l = 0, r = nums.size() - 1;
    while (l < r) {
        int mid = l + r >> 1;
        if (nums[mid] > nums[mid + 1]) r = mid;
        else l = mid + 1;
    }
    return r;
}

时间复杂度:$O(logn)$
空间复杂度:$O(1)$

模板二

模板二是上取整,所以和mid-1比较不会越界

int findPeakElement(vector<int>& nums) {
    int l = 0, r = nums.size() - 1;
    while (l < r) {
        int mid = l + r + 1 >> 1;
        if (nums[mid] > nums[mid - 1]) l = mid;
        else r = mid - 1;
    }
    return l;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录