75. find peak element

explanation

这道题规定一定是先上升,最后下降的数组,一定有peak,且相邻两数不同
找任意一个peak

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class  {

* @param A: An integers array.
* @return: return any of peek positions.
*/
public int findPeak(int[] A) {
// write your code here


保证array中有peak
The numbers in adjacent positions are different.
A[0] < A[1] && A[A.length - 2] > A[A.length - 1].


找到任意一个peak, return index
*/

int start = 0, end = A.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] < A[mid - 1]) {
end = mid; // 不能排除mid
} else {
start = mid;
}
}
if (A[start] < A[end]) {
return end;
} else {
return start;
}

}
}