Skip to content

Commit 5d0d46a

Browse files
authored
Create 0229-majority-element-ii.kt
1 parent f4a0f0d commit 5d0d46a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

kotlin/0229-majority-element-ii.kt

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
fun majorityElement(nums: IntArray): List<Int> {
3+
var count = HashMap<Int, Int>()
4+
5+
for (n in nums) {
6+
count[n] = count.getOrDefault(n, 0) + 1
7+
8+
if (count.size <= 2) continue
9+
10+
var newCount = HashMap<Int, Int>()
11+
for ((n, c) in count) {
12+
if (c > 1)
13+
newCount[n] = c - 1
14+
}
15+
count = newCount
16+
}
17+
18+
var res = mutableListOf<Int>()
19+
20+
for ((n, c) in count) {
21+
var numCount = 0
22+
for (n2 in nums)
23+
if (n == n2)
24+
numCount++
25+
26+
if (numCount > (nums.size / 3)) res.add(n)
27+
}
28+
29+
return res
30+
}
31+
}

0 commit comments

Comments
 (0)