原题链接在这里:https://leetcode.com/problems/peak-index-in-a-mountain-array/

题目:

Let's call an array A a mountain if the following properties hold:

  • A.length >= 3
  • There exists some 0 < i < A.length - 1 such that A[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].

Example 1:

Input: [0,1,0]
Output: 1

Example 2:

Input: [0,2,1,0]
Output: 1

Note:

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

题解:

When finding peak index using binary search, compare A[mid] and A[mid + 1].

If A[mid] < A[mid + 1], peak must on right side of mid, l = mid + 1.

Else, peak must be within mid left side including mid. r = mid.

Time Complexity: O(logn). n = A.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int peakIndexInMountainArray(int[] A) {
 3         if(A == null || A.length == 0){
 4             return -1;
 5         }
 6         
 7         int l = 0;
 8         int r = A.length - 1;
 9         while(l < r){
10             int mid = l + (r - l) / 2;
11             if(A[mid] < A[mid + 1]){
12                 l = mid + 1;
13             }else{
14                 r = mid;
15             }
16         }
17         
18         return l;
19     }
20 }

类似Find Peak Element.