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].
Solution 1:
定义指针index,当数组数值不再增加时(到达顶峰)指针会停止,返回指针数值。
O(n)
class Solution {
public int peakIndexInMountainArray(int[] A) {
if (A == null || A.length == 0)
return 0;
int index = 0;
while (A[index] < A[index + 1])
index++;
return index;
}
}
Solution 2: 二分法
class Solution {
public int peakIndexInMountainArray(int[] A) {
//Binary Search
if(A == null || A.length == 0) return 0;
int left = 0, right = A.length - 1;
while(left <= right){
int mid = (left+right)/2;
if(A[mid] < A[mid+1]) left = mid + 1;
else right = mid - 1;
}
return left;
}
}
O(logn)