8000 :sparkles: Added solution to 414 · ninefive/awesome-golang-leetcode@38fbc51 · GitHub
[go: up one dir, main page]

Skip to content

Commit 38fbc51

Browse files
author
Sathish Babu
committed
✨ Added solution to 414
1 parent 47d7939 commit 38fbc51

File tree

3 files changed

+64
-9
lines changed

3 files changed

+64
-9
lines changed

src/0414.Third-Maximum-Number/README.md

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,37 @@
55
66
## Description
77

8+
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).
9+
810
**Example 1:**
911

1012
```
11-
Input: a = "11", b = "1"
12-
Output: "100"
13+
Input: [3, 2, 1]
14+
15+
Output: 1
16+
17+
Explanation: The third maximum is 1.
18+
```
19+
20+
**Example 2:**
21+
22+
```
23+
Input: [1, 2]
24+
25+
Output: 2
26+
27+
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
28+
```
29+
30+
**Example 3:**
31+
32+
```
33+
Input: [2, 2, 3, 1]
34+
35+
Output: 1
36+
37+
Explanation: Note that the third maximum here means the third maximum distinct number.
38+
Both numbers with value 2 are both considered as second maximum.
1339
```
1440

1541
## 题意
Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,32 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
import "math"
4+
5+
func Solution(nums []int) int {
6+
max1, max2, max3 := math.MinInt64, math.MinInt64, math.MinInt64
7+
n := len(nums)
8+
if n == 0 {
9+
return 0
10+
}
11+
if n == 1 {
12+
return nums[0]
13+
}
14+
for i := 0; i < n; i++ {
15+
if nums[i] >= max1 {
16+
if nums[i] != max1 {
17+
max3, max2, max1 = max2, max1, nums[i]
18+
}
19+
} else if nums[i] >= max2 {
20+
if nums[i] != max2 {
21+
max3, max2 = max2, nums[i]
22+
}
23+
} else if nums[i] > max3 {
24+
max3 = nums[i]
25+
}
26+
}
27+
if max3 != math.MinInt64 {
28+
return max3
29+
} else {
30+
return max1
31+
}
532
}

src/0414.Third-Maximum-Number/Solution_test.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs []int
14+
expect int
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase", []int{3, 2, 1}, 1},
17+
{"TestCase", []int{1, 2}, 2},
18+
{"TestCase", []int{2, 2, 3, 1}, 1},
19+
{"TestCase", []int{1}, 1},
20+
{"TestCase", []int{}, 0},
1921
}
2022

2123
// 开始测试

0 commit comments

Comments
 (0)
0