[LeetCode] Find Peak Element

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.

解题思路:

这道题挺简单的,只要返回其中一个峰值即可。只需最多扫描一次数组。注意特殊情况的处理。

class Solution {
public:
    int findPeakElement(const vector<int> &num) {
        int len=num.size();
        //处理特殊情况
        if(len==0||len==1){
            return 0;
        }
        if(num[0]>num[1]){
            return 0;
        }
        if(num[len-1]>num[len-2]){
            return len-1;
        }
        for(int i=1; i<len-1; i++){
            if(num[i]>num[i-1]&&num[i]>num[i+1]){
                return i;
            }
        }
        return 0;
    }
};
update in 2015.5.20 上述代码的时间复杂度为O(n),感谢网友的提醒。

其实还有一个O(logn),模拟二分法。不过感觉这个题目有点问题:若数组为11111111,那么这个数组就没有峰值了。我们假设相邻元素都不同吧。

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int len = nums.size();
        int start = 0, end = len - 1;
        while(start<=end){
            if(start==end){
                return start;
            }
            int middle = (start + end) / 2;
            if(middle==0 && nums[middle]>nums[middle+1] ||
               middle == len - 1 && nums[middle]>nums[middle-1] ||
               nums[middle] > nums[middle+1] && nums[middle] > nums[middle - 1]
            ){
                return middle;
            }
            if(nums[middle]<nums[middle + 1]){
                start = middle + 1;
            }else{
                end = middle - 1;
            }
        }
        return 0;
    }
};


你可能感兴趣的:(LeetCode,C++)