现在的位置: 首页 > 综合 > 正文

Leetcode Find Peak Element

2018年03月15日 ⁄ 综合 ⁄ 共 1142字 ⁄ 字号 评论关闭

原题:

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.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

题解:

要求log级别的话直接二分就可以,每次二分时判断一下

代码:

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

抱歉!评论已关闭.