Find Peek Element

题目:

There is an integer array which has the following features: The numbers in adjacent positions are different. A[0] < A[1] && A[A.length - 2] > A[A.length - 1]. We define a position P is a peek if: A[P] > A[P-1] && A[P] > A[P+1] Find a peak element in this array. Return the index of the peak.

接口:

class Solution {
public:
    /**
     * @param A: An integers array.
     * @return: return any of peek positions.
     */
    int findPeak(vector<int> A) {
        // write your code here

    }
};

分析:

这题目显然是二分法的第三重境界,每次去掉一半不需要的数据。只要注意不要越界,也就是start = 1, end = A.size() - 2,这样结果基本不会出错。

解法:

class Solution {
public:
    /**
     * @param A: An integers array.
     * @return: return any of peek positions.
     */
    int findPeak(vector<int> A) {
        // write your code here
        if (A.size() == 0) {
            return -1;
        }

        int start = 1;
        int end = A.size() - 2;

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

        if (A[start - 1] < A[start] && A[start + 1] < A[start]) {
            return start;
        } else if (A[end - 1] < A[end] && A[end + 1] < A[end]) {
            return end;
        } else {
            return -1;
        }
    }
};

results matching ""

    No results matching ""