Find Peak Element -- leetcode

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.

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

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

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



算法一,折半查找

如果中间点右邻居小于中间点,则可以排除掉右区间。 因为从中间点往左,必存在一个peak。

如果中间点左邻小于中间点,则可以排除掉左区间。  因为从中间点往右,必存在一个peak。

需要特殊注意的事,当区间只剩2个元素时,此时左端点和中间点是同一个端点。需要特殊处理一下。

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int left = 0;
        int right = nums.size()-1;
        while (left < right) {
            const int mid = left + (right - left) / 2;
            if (nums[mid+1] < nums[mid])
                right = mid;
            else if (left != mid)
                left = mid;
            else
                return nums[left] > nums[right] ? left : right;
        }
        return left;
    }
};

上面问题在于,当left和mid相等时,不特殊处理,会出现死循环。

可以改进一下判断条件, 当中间点右邻居大于中间点时,抛弃左边区间以及中间点。 即,连同中间点也进行抛弃。

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int left = 0;
        int right = nums.size()-1;
        while (left < right) {
            const int mid = left + (right - left) / 2;
            if (nums[mid+1] > nums[mid])
                left = mid+1;
            else
                right = mid;
        }
        return left;
    }
};


算法二,顺序查找

找到第一个元素,它大于它的右邻居。

即找到满足升序排列的右边界。

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int peak = 0;
        const int bound = nums.size()-1;
        while (peak < bound && nums[peak] < nums[peak+1])
            ++peak;
            
        return peak;
    }
};

此算法为O(n),虽不及算法一,但也是一种思路。而实际在leetcode上,运行时间并不多于前一算法。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值