There is an integer array which has the following features:
- The numbers in adjacent positions are different.
- A[0] < A[1] && A[A.length - 2] > A[A.length - 1].
We define a position P is a peek if:
A[P] > A[P-1] && A[P] > A[P+1]
Find a peak element in this array. Return the index of the peak.
Example
Given [1, 2, 1, 3, 4, 5, 7,
6]
Return index 1
(which
is number 2) or 6
(which is number 7)
二分法查找,添加布尔型返回值,让查找到true时可以马上返回停止继续查找。、
class Solution {
/**
* @param A: An integers array.
* @return: return any of peek positions.
*/
public int findPeak(int[] A) {
if(A.length < 3) return -1;
int left = 0, right = A.length - 1;
List<Integer> res = new ArrayList<Integer>();
helper(A, left, right, res);
return res.get(0);
}
boolean helper(int[] A, int left, int right, List<Integer> res) {
if(left > right) return false;
int mid = (left + right) / 2;
if(mid - 1 >= 0 && mid + 1 <= A.length - 1 && A[mid - 1] < A[mid] &&
A[mid + 1] < A[mid]) {res.add(mid); return true;};
return helper(A, left, mid - 1, res) || helper(A, mid + 1, right, res);
}
}