Let's call an arrayAamountain if the following properties hold:

  • A.length >= 3There exists some0 < i < A.length - 1such thatA[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]

Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].

Note:

  1. 3 <= A.length <= 10000
  2. 0 <= A[i] <= 10^6
  3. A is a mountain, as defined above.

1.暴力解法

从头开始找,直到A[i] > A[i + 1]

class Solution {
    public int peakIndexInMountainArray(int[] A) {
        int i = 0;
        while(i < A.length - 1 && A[i] < A[i + 1])
            i++;

        return i;
    }
}

2.二分搜索

初始的范围为整个数组,每次取整个范围的中点,检查是不是mountain的peak,如果是直接返回,如果不是peak,可以根据中点两边的值判断peak在左边一半还是右边一半,进而调整范围

class Solution {
    public int peakIndexInMountainArray(int[] A) {
        int left = 0;
        int right = A.length - 1;

        while(left < right - 1) {
            int mid = left + (right - left) / 2;

            if(A[mid] > A[mid - 1] && A[mid] > A[mid + 1])
                return mid;

            if(A[mid] > A[mid + 1])
                right = mid;
            else
                left = mid;
        }

        return A[left] > A[right] ? left : right;
    }
}

results matching ""

    No results matching ""