Skip to content

Commit f86ceb9

Browse files
aQuaaQua
aQua
authored and
aQua
committed
229 finish
1 parent ae2ed4b commit f86ceb9

File tree

1 file changed

+34
-9
lines changed

1 file changed

+34
-9
lines changed
Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,48 @@
11
package Problem0229
22

33
func majorityElement(a []int) []int {
4-
l := len(a)
5-
if l < 2 {
4+
if len(a) <= 1 {
65
return a
76
}
87

8+
e1, e2, c1, c2 := 0, 1, 0, 0
9+
for _, e := range a {
10+
switch {
11+
case e == e1:
12+
c1++
13+
case e == e2:
14+
c2++
15+
case c1 == 0:
16+
e1 = e
17+
c1 = 1
18+
case c2 == 0:
19+
e2 = e
20+
c2 = 1
21+
default:
22+
c1--
23+
c2--
24+
}
25+
}
26+
927
res := []int{}
10-
rec := make(map[int]int, l)
1128

12-
for i := 0; i < l; i++ {
13-
rec[a[i]]++
29+
if maj(a, e2) {
30+
res = append(res, e2)
1431
}
1532

16-
for k, n := range rec {
17-
if 3*n > l {
18-
res = append(res, k)
19-
}
33+
if maj(a, e1) {
34+
res = append(res, e1)
2035
}
2136

2237
return res
2338
}
39+
40+
func maj(a []int, n int) bool {
41+
c := 0
42+
for _, e := range a {
43+
if e == n {
44+
c++
45+
}
46+
}
47+
return c > (len(a) / 3)
48+
}

0 commit comments

Comments
 (0)