8000 add 162 solution · Feng2012/awesome-golang-leetcode@8846aa9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 8846aa9

Browse files
author
Wave
committed
add 162 solution
1 parent f2e26ad commit 8846aa9

File tree

3 files changed

+112
-0
lines changed

3 files changed

+112
-0
lines changed

src/0162.Find-Peak-Element/README.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# [162. Find Peak Element][title]
2+
3+
## Description
4+
5+
峰值定义为比左右相邻元素大的元素。
6+
给定一个数组 nums,保证 nums[i] ≠ nums[i+1],请找出该数组的峰值,并返回峰值的下标。
7+
数组中可能包含多个峰值,只需返回任意一个即可。
8+
假定 nums[-1] = nums[n] = -∞。
9+
10+
**Example 1:**
11+
12+
```
13+
输入:nums = [1,2,3,1]
14+
输出:2
15+
解释:3是一个峰值,3的下标是2。
16+
```
17+
18+
**Example 2:**
19+
20+
```
21+
输入:nums = [1,2,1,3,5,6,4]
22+
输出:1 或 5
23+
解释:数组中有两个峰值:1或者5,返回任意一个即可。
24+
```
25+
26+
**Tags:** Math, String
27+
28+
## 题意
29+
> (二分) O(logn)O(logn)
30+
仔细分析我们会发现:
31+
32+
- 如果 `nums[i-1] < nums[i]`,则如果 `nums[i-1], nums[i], ... nums[n-1]` 是单调的,则 `nums[n-1]`就是峰值;如果`nums[i-1]`, `nums[i], ... nums[n-1]`不是单调的,则从 ii 开始,第一个满足 `nums[i] > nums[i+1]`的 ii 就是峰值;所以 `[i,n−1][i,n−1]` 中一定包含一个峰值;
33+
- 如果 `nums[i-1] > nums[i]`,同理可得 `[0,i−1][0,i−1]` 中一定包含一个峰值;
34+
35+
所以我们可以每次二分中点,通过判断 `nums[i-1]``nums[i]` 的大小关系,可以判断左右两边哪边一定有峰值,从而可以将检索区间缩小一半。
36+
时间复杂度分析:二分检索,每次删掉一半元素,所以时间复杂度是 `O(logn)`
37+
38+
## 题解
39+
40+
### 思路1
41+
> 。。。。
42+
43+
```go
44+
45+
```
46+
47+
### 思路2
48+
> 思路2
49+
```go
50+
51+
```
52+
53+
## 结语
54+
55+
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-leetcode][me]
56+
57+
[title]: https://leetcode.com/problems/find-peak-element/
58+
[me]: https://github.com/kylesliu/awesome-golang-leetcode
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package Solution
2+
3+
func findPeakElement(nums []int) int {
4+
l, r := 0, len(nums)-1
5+
for l < r {
6+
mid := (l + r + 1) / 2
7+
if nums[mid] > nums[mid-1] {
8+
l = mid
9+
} else {
10+
r = mid - 1
11+
}
12+
}
13+
return l
14+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package Solution
2+
3+
import (
4+
"reflect"
5+
"strconv"
6+
"testing"
7+
)
8+
9+
func TestSolution(t *testing.T) {
10+
// 测试用例
11+
cases := []struct {
12+
name string
13+
inputs []int
14+
expect int
15+
}{
16+
{"TestCase", []int{1, 2, 3, 1}, 2},
17+
{"TestCase", []int{1, 2, 1, 3, 5, 6, 4}, 5},
18+
}
19+
20+
// 开始测试
21+
for i, c := range cases {
22+
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
23+
got := findPeakElement(c.inputs)
24+
if !reflect.DeepEqual(got, c.expect) {
25+
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
26+
c.expect, got, c.inputs)
27+
}
28+
})
29+
}
30+
}
31+
32+
// 压力测试
33+
func BenchmarkSolution(b *testing.B) {
34+
35+
}
36+
37+
// 使用案列
38+
func ExampleSolution() {
39+
40+
}

0 commit comments

Comments
 (0)
0