Skip to content

Commit ae2ed4b

Browse files
aQuaaQua
aQua
authored and
aQua
committed
229 accepted
1 parent 64bc427 commit ae2ed4b

File tree

3 files changed

+88
-0
lines changed

3 files changed

+88
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# [229. Majority Element II](https://leetcode.com/problems/majority-element-ii/)
2+
3+
## 题目
4+
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
5+
6+
## 解题思路
7+
8+
见程序注释
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package Problem0229
2+
3+
func majorityElement(a []int) []int {
4+
l := len(a)
5+
if l < 2 {
6+
return a
7+
}
8+
9+
res := []int{}
10+
rec := make(map[int]int, l)
11+
12+
for i := 0; i < l; i++ {
13+
rec[a[i]]++
14+
}
15+
16+
for k, n := range rec {
17+
if 3*n > l {
18+
res = append(res, k)
19+
}
20+
}
21+
22+
return res
23+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package Problem0229
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_Problem0229(t *testing.T) {
26+
ast := assert.New(t)
27+
28+
qs := []question{
29+
30+
question{
31+
para{
32+
[]int{1, 1, 1, 2, 2, 3, 3, 3},
33+
},
34+
ans{
35+
[]int{1, 3},
36+
},
37+
},
38+
39+
question{
40+
para{
41+
[]int{1, 3},
42+
},
43+
ans{
44+
[]int{1, 3},
45+
},
46+
},
47+
48+
// 如需多个测试,可以复制上方元素。
49+
}
50+
51+
for _, q := range qs {
52+
a, p := q.ans, q.para
53+
fmt.Printf("~~%v~~\n", p)
54+
55+
ast.Equal(a.one, majorityElement(p.nums), "输入:%v", p)
56+
}
57+
}

0 commit comments

Comments
 (0)