File tree Expand file tree Collapse file tree 2 files changed +16
-27
lines changed
Algorithms/0162.find-peak-element Expand file tree Collapse file tree 2 files changed +16
-27
lines changed Original file line number Diff line number Diff line change 17
17
Your solution should be in logarithmic complexity.
18
18
19
19
20
- Credits: Special thanks to @ts for adding this problem and creating all test cases.
21
-
22
20
## 解题思路
23
-
21
+ 注意理解题意,题目要求,
22
+ 1 . 返回任意一个局部高点即可
23
+ 1 . 要求程序的复杂度为O(logN)
24
24
见程序注释
Original file line number Diff line number Diff line change 1
1
package Problem0162
2
2
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
5
7
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
27
15
}
16
+ mid = (high + low ) / 2
28
17
}
29
18
30
- return 0
19
+ return low + 1
31
20
}
You can’t perform that action at this time.
0 commit comments