Skip to content

Commit 920d92b

Browse files
committed
top k frequent elements
1 parent 40c2fe9 commit 920d92b

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
import java.util.*
6+
7+
/**
8+
* Leetcode
9+
* 347. Top K Frequent Elements
10+
* Medium
11+
*/
12+
class TopKFrequentElements {
13+
/**
14+
* Runtime: 30 ms(Beats: 68.62 %)
15+
* Time Complexity: O(n log n)
16+
* - list 정렬
17+
*
18+
* Memory: 42.20 MB(Beats: 58.82 %)
19+
* Space Complexity: O(n)
20+
*/
21+
fun topKFrequent(nums: IntArray, k: Int): IntArray {
22+
val countMap: MutableMap<Int, Int> = HashMap()
23+
24+
for (num in nums) {
25+
countMap[num] = countMap.getOrDefault(num, 0) + 1
26+
}
27+
28+
val list = mutableListOf<Node>()
29+
for (key in countMap.keys) {
30+
list.add(Node(key, countMap[key]!!))
31+
}
32+
list.sortDescending()
33+
34+
val answer = IntArray(k)
35+
for (i in 0 until k) {
36+
answer[i] = list[i].value
37+
}
38+
return answer
39+
}
40+
41+
/**
42+
* 개선된 버전: 우선순위 큐를 사용
43+
*
44+
* Runtime: 19 ms(Beats: 96.30 %)
45+
* Time Complexity: O(n log n)
46+
*
47+
* Memory: 44.83 MB(Beats: 18.35 %)
48+
* Space Complexity: O(n)
49+
*/
50+
fun topKFrequent2(nums: IntArray, k: Int): IntArray {
51+
val countMap = nums.groupBy { it }
52+
.mapValues { it.value.size }
53+
54+
val pq = PriorityQueue<Node>(compareByDescending { it.count })
55+
countMap.forEach { (num, count) ->
56+
pq.offer(Node(num, count))
57+
}
58+
59+
return IntArray(k) { pq.poll().value }
60+
}
61+
62+
data class Node(var value: Int, var count: Int) : Comparable<Node> {
63+
override fun compareTo(other: Node): Int {
64+
return this.count.compareTo(other.count)
65+
}
66+
}
67+
68+
@Test
69+
fun test() {
70+
topKFrequent(intArrayOf(1, 1, 1, 2, 2, 3), 2) shouldBe intArrayOf(1, 2)
71+
topKFrequent(intArrayOf(1), 1) shouldBe intArrayOf(1)
72+
73+
topKFrequent2(intArrayOf(1, 1, 1, 2, 2, 3), 2) shouldBe intArrayOf(1, 2)
74+
topKFrequent2(intArrayOf(1), 1) shouldBe intArrayOf(1)
75+
}
76+
}

0 commit comments

Comments
 (0)