Skip to content

Commit a21e0d9

Browse files
aQuaaQua
aQua
authored and
aQua
committed
162 finish
1 parent 1f91c47 commit a21e0d9

File tree

2 files changed

+16
-27
lines changed

2 files changed

+16
-27
lines changed

Algorithms/0162.find-peak-element/README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ Note:
1717
Your solution should be in logarithmic complexity.
1818

1919

20-
Credits:Special thanks to @ts for adding this problem and creating all test cases.
21-
2220
## 解题思路
23-
21+
注意理解题意,题目要求,
22+
1. 返回任意一个局部高点即可
23+
1. 要求程序的复杂度为O(logN)
2424
见程序注释
Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,20 @@
11
package Problem0162
22

3-
func findPeakElement(a []int) int {
4-
n := len(a)
3+
func findPeakElement(nums []int) int {
4+
low := -1
5+
high := len(nums)
6+
mid := (low + high) / 2
57

6-
if n <= 1 {
7-
return 0
8-
}
9-
// gtl: greater than left
10-
gtl := make([]bool, n)
11-
// a[-1] == -∞
12-
gtl[0] = true
13-
14-
// gtr: greater than right
15-
gtr := make([]bool, n)
16-
// a[l] == -∞
17-
gtr[n-1] = true
18-
19-
for i := 1; i < n; i++ {
20-
gtl[i] = a[i] > a[i-1]
21-
gtr[n-i-1] = a[n-i-1] > a[n-i]
22-
}
23-
24-
for i := 0; i < n; i++ {
25-
if gtl[i] && gtr[i] {
26-
return i
8+
// low +2 < high
9+
// low + 1 <= mid < high -1
10+
for low+1 <= mid && mid < high-1 {
11+
if nums[mid] < nums[mid+1] {
12+
low = mid
13+
} else {
14+
high = mid + 1
2715
}
16+
mid = (high + low) / 2
2817
}
2918

30-
return 0
19+
return low + 1
3120
}

0 commit comments

Comments
 (0)