852. Peak Index in a Mountain Array - Easy

用binary search

如果A[mid] < A[mid+1],说明peak在mid右侧,l = mid + 1;否则说明peak在mid右侧,r = mid

时间:O(N),空间:O(1)

class Solution {
    public int peakIndexInMountainArray(int[] A) {
        int l = 0, r = A.length - 1;
        while(l < r) {
            int mid = l + (r - l) / 2;
            if(A[mid] < A[mid + 1])
                l = mid + 1;
            else
                r = mid;
        }
        return l;
    }
}

 

posted @ 2018-12-02 12:10  fatttcat  阅读(106)  评论(0编辑  收藏  举报