LeetCode: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.

// Source : https://oj.leetcode.com/problems/find-peak-element/
// Author : Chao Zeng
// Date   : 2014-12-25

class Solution {
public:
    int findPeakElement(const vector<int> &num) {
        int n = num.size();
        if (n==1) return 0;
        if (n==2){
            if (num[1] > num[0]) return 1;
            if (num[0] > num[1]) return 0;
        }
        for (int i = 1; i < n - 1; i++){
            if (num[i] > num[i-1] && num[i] > num[i+1])
                return i;
        }
        if (num[n-1] > num[n-2])
            return n-1;
    }
};

// Source : https://oj.leetcode.com/problems/find-peak-element/
// Author : Chao Zeng
// Date   : 2014-12-25

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


你可能感兴趣的:(LeetCode,二分查找)