Skip to content

Commit 0cb9c9c

Browse files
aQuaaQua
aQua
authored and
aQua
committed
169 accepted
1 parent fbe6757 commit 0cb9c9c

File tree

3 files changed

+101
-0
lines changed

3 files changed

+101
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# [169. Majority Element](https://leetcode.com/problems/majority-element/)
2+
3+
## 题目
4+
5+
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
6+
7+
You may assume that the array is non-empty and the majority element always exist in the array.
8+
9+
## 解题思路
10+
11+
12+
见程序注释
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package Problem0169
2+
3+
func majorityElement(nums []int) int {
4+
n := len(nums)
5+
times := n / 2
6+
m := make(map[int]int, times)
7+
8+
for _, n := range nums {
9+
if m[n]+1 > times {
10+
return n
11+
}
12+
m[n]++
13+
}
14+
15+
max, res := 0, 0
16+
for i, v := range m {
17+
if max < v {
18+
max = v
19+
res = i
20+
}
21+
}
22+
23+
return res
24+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package Problem0169
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type question struct {
11+
para
12+
ans
13+
}
14+
15+
// para 是参数
16+
type para struct {
17+
nums []int
18+
}
19+
20+
// ans 是答案
21+
type ans struct {
22+
one int
23+
}
24+
25+
func Test_Problem0169(t *testing.T) {
26+
ast := assert.New(t)
27+
28+
qs := []question{
29+
30+
question{
31+
para{
32+
[]int{1},
33+
},
34+
ans{
35+
1,
36+
},
37+
},
38+
39+
question{
40+
para{
41+
[]int{1, 1, 2, 2},
42+
},
43+
ans{
44+
1,
45+
},
46+
},
47+
question{
48+
para{
49+
[]int{1, 2, 2},
50+
},
51+
ans{
52+
2,
53+
},
54+
},
55+
56+
// 如需多个测试,可以复制上方元素。
57+
}
58+
59+
for _, q := range qs {
60+
a, p := q.ans, q.para
61+
fmt.Printf("~~%v~~\n", p)
62+
63+
ast.Equal(a.one, majorityElement(p.nums), "输入:%v", p)
64+
}
65+
}

0 commit comments

Comments
 (0)