【两次过】Lintcode 75. 寻找峰值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/84874469

你给出一个整数数组(size为n),其具有以下特点:

  • 相邻位置的数字是不同的
  • A[0] < A[1] 并且 A[n - 2] > A[n - 1]

假定P是峰值的位置则满足A[P] > A[P-1]A[P] > A[P+1],返回数组中任意一个峰值的位置。

样例

给出数组[1, 2, 1, 3, 4, 5, 7, 6]返回1, 即数值 2 所在位置, 或者6, 即数值 7 所在位置.

挑战

Time complexity O(logN)

注意事项

  • It's guaranteed the array has at least one peak.
  • The array may contain multiple peeks, find any of them.
  • The array has at least 3 numbers in it.

解题思路:

普通遍历方法会超时。所以这里采用二分搜索法,如果中间的数就是峰值直接返回,如果中间的数比前一位数小的话,peek点肯定在mid右边,如果中间的数比后一位数大的话,peek点肯定在mid左边

public class Solution {
    /**
     * @param A: An integers array.
     * @return: return any of peek positions.
     */
    public int findPeak(int[] A) {
        // write your code here
        int l = 1, r = A.length-2; 
        
        while(l <  r) {
            
            int mid = (l + r) / 2;

            if(A[mid] > A[mid-1] && A[mid] > A[mid+1])
                return mid;
            else if(A[mid] < A[mid - 1]) //如果中间的数比前一位数小的话,peek点肯定在mid右边
                r = mid;
            else                        //如果中间的数比后一位数大的话,peek点肯定在mid左边
                l = mid + 1;
        }
        
        return l;
    }
    

}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/84874469