您的位置:首页 > 其它

Find Peak Element -- leetcode

2015-06-21 09:02 465 查看
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
 = -∞
.

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上,运行时间并不多于前一算法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: