Find Peak Element

O(logN)

Check four different situations:

1) The peek

2) increasing section

3) decreasing section

4) minimum

class Solution {
    /**
     * @param A: An integers array.
     * @return: return any of peek positions.
     */
    public int findPeak(int[] A) {
        // write your code here
        if (A == null || A.length == 0) {
            return -1;
        }
        
        int start = 0;
        int end = A.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] > A[mid - 1] && A[mid] > A[mid + 1]) {
                return mid;
            } else if (A[mid] > A[mid - 1] && A[mid] < A[mid + 1]) {
                start = mid;
            } else if (A[mid] < A[mid - 1] && A[mid] > A[mid + 1]) {
                end = mid;
            } else {
                end = mid;
            }
        }
        
        if (A[start] > A[end]) {
            return start;
        }
        if (A[end] > A[start]) {
            return end;
        }
        return -1;
    }
}

 

posted on 2017-05-04 06:16  codingEskimo  阅读(76)  评论(0编辑  收藏  举报

导航