LeetCode(162) 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.
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.


分析如下:

逐个元素扫描的时间复杂度是O(N),二分查找时间复杂度是O(lgN),所以该使用二分查找。

有人可能有疑问,如果有多个波峰,那么二分查找还有效吗?对本题而言,依然有效,因为题目只让你返回一个peak,不是所有的peak。满足下面的代码条件的点必然是peak中的一个。

狗狗到一个MIT讲peak element的资料, 写得十分清楚。


我的代码:

// 40ms
class Solution {
public:
    int findPeakElement(const vector<int> &num, int start, int end) {
        int mid = start + (end - start) / 2;
        if (mid == 0 && num[mid] >= num[mid + 1]) return mid;
        else if (mid == num.size() -1 && num[mid] > num[mid - 1]) return mid;
        else if (num[mid] >= num[mid - 1] && num[mid] >= num[mid + 1]) return mid; //这里是>=和<=
        else if (mid > 0 && num[mid] < num[mid - 1]) return findPeakElement(num, start, mid - 1); 
        //注意mid > 0和num[mid] < num[mid - 1]是搭配出现的,这样才逻辑正确。一开始把这行和下面行写串了所以错误。
        else if (mid < num.size() -1 && num[mid] < num[mid + 1]) return findPeakElement(num, mid + 1, end);;
    }
    int findPeakElement(const vector<int> &num) {
        if (num.size() == 1) return 0;
        return findPeakElement(num, 0, num.size() - 1);
    }
};


参考资料:

1 MIT lecture

你可能感兴趣的:(LeetCode)