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(lgN)。因此,可以採用二分查找法,即:

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

包含一個局部最大值。

代碼:

#include <iostream>
#include <vector>
using namespace std;

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;
    }
}

int main()
{
    vector<int> num;
    int x;
    while(cin >> x)
    {
        num.push_back(x);
    }
    cout<<findPeakElement(num);
}




發佈了81 篇原創文章 · 獲贊 51 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章