-
Notifications
You must be signed in to change notification settings - Fork 71
/
Question07FindPeakElement.java
44 lines (42 loc) · 1.28 KB
/
Question07FindPeakElement.java
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
35
36
37
38
39
40
41
42
43
44
package ninechapter.ch02_binary_search_and_sorted_array;
/**
* 寻找峰值
* http://www.lintcode.com/zh-cn/problem/find-peak-element/
* 你给出一个整数数组(size为n),其具有以下特点:
* 相邻位置的数字是不同的
* A[0] < A[1] 并且 A[n - 2] > A[n - 1]
* 假定P是峰值的位置则满足A[P] > A[P-1]且A[P] > A[P+1],返回数组中任意一个峰值的位置。
* <p>
* --------
* 给出数组[1, 2, 1, 3, 4, 5, 7, 6]返回1, 即数值 2 所在位置, 或者6, 即数值 7 所在位置.
* Created by anduo on 17-3-13.
*/
public class Question07FindPeakElement {
/**
* @param A: An integers array.
* @return: return any of peek positions.
*/
public int findPeak(int[] A) {
// 局部有序
if (A == null || A.length == 0) {
return -1;
}
int start = 1;
int end = A.length - 2;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] < A[mid - 1]) {
end = mid;
} else if (A[mid] < A[mid + 1]) {
start = mid;
} else {
end = mid;
}
}
if (A[start] < A[end]) {
return end;
} else {
return start;
}
}
}