Skip to content

Commit b9aa5d7

Browse files
aQuaaQua
aQua
authored and
aQua
committed
169 finish
1 parent d9e81e7 commit b9aa5d7

File tree

2 files changed

+28
-9
lines changed

2 files changed

+28
-9
lines changed
Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,26 @@
11
package Problem0169
22

33
func majorityElement(nums []int) int {
4-
n := len(nums)
5-
times := n / 2
6-
m := make(map[int]int, times)
4+
// 根据题意 len[nums] > 0 且 出现次数大于 n/2 的元素存在。
5+
x, t := nums[0], 1
76

8-
for _, n := range nums {
9-
if m[n]+1 > times {
10-
return n
7+
for i := 1; i < len(nums); i++ {
8+
switch {
9+
case x == nums[i]:
10+
t++
11+
case t > 0:
12+
t--
13+
default:
14+
// 此时 x != nums[i] 且 t == 0
15+
// 可知 i 必定为 偶数
16+
// 假设 nums 中出现最多的元素是 z,其出现次数为 zn > n/2
17+
// 在 nums[:i] 中,z 出现次数 <=i/2
18+
// 那么,在 nums[i:] 中,z 出现的次数 >= zn - i/2 > n/2 - i/2 = (n-i)/2
19+
// 即 z 在 nums[i:] 中出现的次数,依然超过了 len(nums[i:])/2
20+
x = nums[i]
21+
t = 1
1122
}
12-
m[n]++
1323
}
1424

15-
return 0
25+
return x
1626
}

Algorithms/0169.majority-element/majority-element_test.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,15 @@ func Test_Problem0169(t *testing.T) {
2727

2828
qs := []question{
2929

30+
question{
31+
para{
32+
[]int{1, 1, 2, 2, 2, 1, 1, 2, 2},
33+
},
34+
ans{
35+
2,
36+
},
37+
},
38+
3039
question{
3140
para{
3241
[]int{1},
@@ -44,7 +53,7 @@ func Test_Problem0169(t *testing.T) {
4453
2,
4554
},
4655
},
47-
56+
4857
question{
4958
para{
5059
[]int{1, 2, 2},

0 commit comments

Comments
 (0)