Skip to content

Commit 192d7d5

Browse files
author
이연수
committed
Top K Frequent Elements
1 parent 6dbea54 commit 192d7d5

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)