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 bb37caa commit 4f7a22dCopy full SHA for 4f7a22d
1 file changed
top-k-frequent-elements/acious.kt
@@ -0,0 +1,19 @@
1
+class Solution {
2
+ // 시간복잡도 : O(n) : map 세팅, O(nlogn) : map value 정렬 = O(nlogn)
3
+ fun topKFrequent(nums: IntArray, k: Int): IntArray {
4
+ val map = mutableMapOf<Int, Int>()
5
+
6
+ for (num in nums) {
7
+ // 더 효율적이고 가독성 좋은 getOrDefault 사용
8
+ map[num] = map.getOrDefault(num, 0) + 1
9
+ }
10
11
+ // 1. value를 기준으로 내림차순 정렬 후 key만 추출
12
+ val sortedKeys = map.entries
13
+ .sortedByDescending { it.value }
14
+ .map { it.key }
15
16
+ // 2. 0부터 k개(0 until k)를 자르고 IntArray로 변환
17
+ return sortedKeys.slice(0 until k).toIntArray()
18
19
+}
0 commit comments