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.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.

這道題簡單的來想就是  遍歷一遍數組O(N)的複雜度,但是題目要求是O(logN)的複雜度。

那麼我們就可以想了,如果中間元素大於其相鄰後續元素,則中間元素左側(包含該中間元素)必包含一個局部最大值

如果中間元素小於其相鄰後續元素,則中間元素右側必包含一個局部最大值。

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

這道題挺不錯的,算是用了二分查找的思想


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章