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

Diffculty
Medium

Similar Problems
None

Analysis

注意題中的关键条件:A[-1] = A[n] = -∞, 即A[-1] < A[0] && A[n] < A[n - 1], 如果没有规定数组A[0]前和A[n-1]后的元素均为负无穷,那么在数组是单调序列的情況下,就没有峰值了

Solutions
class Solution {
public:
    int findPeakElement(vector<int>& A) {
        int n = A.size();
        if (n == 0) return -1;

        int start = 0, end = n - 1, mid = end / 2;
        while (start < end) {
            if (A[mid] < A[mid + 1]) {
                start = mid + 1;
            } else {
                end = mid;
            }
            mid = start + (end - start) / 2;
        }

        return start;
    }
};
Reference

results matching ""

    No results matching ""