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 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]
.
Example 1:
Input: [0,1,0]
Output: 1
Example 2:
Input: [0,2,1,0]
Output: 1
1 //linear approach: Time: O(n), Space: O(1) 2 public int peakIndexInMountainArray(int[] A) { 3 if (A == null || A.length == 0) { 4 return -1; 5 } 6 7 for (int i = 0; i < A.length - 1; i++) { 8 if (A[i] > A[i + 1]) { 9 return i; 10 } 11 } 12 13 return -1; 14 } 15 16 //binary search approach: Time: O(logn), Space: O(1) 17 public int peakIndexInMountainArray(int[] A) { 18 if (A == null || A.length == 0) { 19 return -1; 20 } 21 22 int start = 0; 23 int end = A.length - 1; 24 25 while (start < end) { 26 int mid = start + (end - start) / 2; 27 if (A[mid] < A[mid + 1]) { 28 start = mid + 1;//注意start是指到mid + 1, 而end是指到mid 29 } else if (A[mid] > A[mid + 1]) { 30 end = mid; 31 } else { 32 return mid;//这里题目表示没有两个数相等的情况,但为了严谨可以加上这句 33 } 34 } 35 36 return start;//返回start和end都可以,因为while停止的条件就是start = end了 37 } 39 //注: test cases: 40 //[0,1,0] 奇数情况 41 //[0,1,2,0] 偶数情况
similar: 162. Find Peak Element