We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 6dbea54 commit 192d7d5Copy full SHA for 192d7d5
top-k-frequent-elements/EcoFriendlyAppleSu.kt
@@ -0,0 +1,23 @@
1
+package leetcode_study
2
+
3
+/**
4
+ * 주어진 숫자들에서 빈도 수가 가장 큰 k 개의 숫자를 구하는 문제. map 자료구조를 사용해 해결
5
+ * 시간 복잡도 : O(n)
6
+ * -> Int Array를 순회해 map에 담는 과정
7
+ * 공간 복잡도 : O(n)
8
+ * -> Int Array에 존재하는 유니크한 요소 만큼 필요함.
9
+ */
10
+fun topKFrequent(nums: IntArray, k: Int): IntArray {
11
+ val map = mutableMapOf<Int, Int>()
12
13
+ for (i in nums.indices) {
14
+ if (map.containsKey(nums[i])) {
15
+ val value = map[nums[i]]!!
16
+ map[nums[i]] = value + 1
17
+ } else {
18
+ map.putIfAbsent(nums[i], 1)
19
+ }
20
21
+ val sortedMap = map.toList().sortedByDescending { it.second }.toMap()
22
+ return sortedMap.entries.take(k).map { it.key }.toIntArray()
23
+}
0 commit comments