Skip to content

Commit ccf3e34

Browse files
committed
添加 problem 414
1 parent 3cacb79 commit ccf3e34

File tree

3 files changed

+122
-0
lines changed

3 files changed

+122
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package leetcode
2+
3+
import (
4+
"math"
5+
)
6+
7+
func thirdMax(nums []int) int {
8+
a, b, c := math.MinInt64, math.MinInt64, math.MinInt64
9+
for _, v := range nums {
10+
if v > a {
11+
c = b
12+
b = a
13+
a = v
14+
} else if v < a && v > b {
15+
c = b
16+
b = v
17+
} else if v < b && v > c {
18+
c = v
19+
}
20+
}
21+
if c == math.MinInt64 {
22+
return a
23+
}
24+
return c
25+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package leetcode
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
type question414 struct {
9+
para414
10+
ans414
11+
}
12+
13+
// para 是参数
14+
// one 代表第一个参数
15+
type para414 struct {
16+
one []int
17+
}
18+
19+
// ans 是答案
20+
// one 代表第一个答案
21+
type ans414 struct {
22+
one int
23+
}
24+
25+
func Test_Problem414(t *testing.T) {
26+
27+
qs := []question414{
28+
29+
question414{
30+
para414{[]int{1, 1, 2}},
31+
ans414{2},
32+
},
33+
34+
question414{
35+
para414{[]int{3, 2, 1}},
36+
ans414{1},
37+
},
38+
39+
question414{
40+
para414{[]int{1, 2}},
41+
ans414{2},
42+
},
43+
44+
question414{
45+
para414{[]int{2, 2, 3, 1}},
46+
ans414{1},
47+
},
48+
}
49+
50+
fmt.Printf("------------------------Leetcode Problem 414------------------------\n")
51+
52+
for _, q := range qs {
53+
_, p := q.ans414, q.para414
54+
fmt.Printf("【input】:%v 【output】:%v\n", p, thirdMax(p.one))
55+
}
56+
fmt.Printf("\n\n\n")
57+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# [414. Third Maximum Number](https://leetcode.com/problems/third-maximum-number/)
2+
3+
## 题目
4+
5+
Given a **non-empty** array of integers, return the **third** maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
6+
7+
**Example 1:**
8+
9+
Input: [3, 2, 1]
10+
11+
Output: 1
12+
13+
Explanation: The third maximum is 1.
14+
15+
**Example 2:**
16+
17+
Input: [1, 2]
18+
19+
Output: 2
20+
21+
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
22+
23+
**Example 3:**
24+
25+
Input: [2, 2, 3, 1]
26+
27+
Output: 1
28+
29+
Explanation: Note that the third maximum here means the third maximum distinct number.
30+
Both numbers with value 2 are both considered as second maximum.
31+
32+
33+
## 题目大意
34+
35+
给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是 O(n)。
36+
37+
38+
## 解题思路
39+
40+
- 水题,动态维护 3 个最大值即可。注意数组中有重复数据的情况。如果只有 2 个数或者 1 个数,则返回 2 个数中的最大值即可。

0 commit comments

Comments
 (0)