Skip to content

Commit 100b8bb

Browse files
author
이연수
committed
Top K Frequent Element 피드백 반영
1 parent 3f8adfa commit 100b8bb

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

top-k-frequent-elements/EcoFriendlyAppleSu.kt

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package leetcode_study
22

33
/**
44
* 주어진 숫자들에서 빈도 수가 가장 큰 k 개의 숫자를 구하는 문제. map 자료구조를 사용해 해결
5-
* 시간 복잡도 : O(n)
5+
* 시간 복잡도 : O(nlogn)
66
* -> Int Array를 순회해 map에 담는 과정 O(n)
77
* -> 채워진 Map 자료구조에서 value 기준 내림차순으로 정렬 과정 O(nlogn)
88
* -> 정렬된 Map에서 K 만큼 값을 가져오는 과정 O(K). (k는 상수)
@@ -24,3 +24,39 @@ fun topKFrequent(nums: IntArray, k: Int): IntArray {
2424
val sortedMap = map.toList().sortedByDescending { it.second }.toMap()
2525
return sortedMap.entries.take(k).map { it.key }.toIntArray()
2626
}
27+
28+
/**
29+
* 주어진 수의 빈도수를 기준으로 숫자를 할당하고 내림차순으로 순회해 k 개의 숫자를 얻게 되면 답을 도출하는 방법
30+
* 시간 복잡도 : O(n)
31+
* -> Int Array를 순회해 map에 담는 과정 O(n)
32+
* -> 빈도수 배열에 값을 채우는 과정 O(n)
33+
* -> 빈도수 배열을 내림차순으로 순회해 k 개를 만족하면 답을 도출하는 과정 O(n).
34+
* 이중 for loop 이지만 실제로는 빈도수가 유일한 숫자들만 고려되므로 k가 n보다 작거나 같은 경우에는 O(n)으로 가늠할 수 있음.
35+
* 각 단계의 시간 복잡도를 더하면 : O(n) + O(n) + O(n) -> O(n)
36+
* 공간 복잡도 : O(n)
37+
* -> Int Array에 존재하는 유니크한 요소 만큼 필요함.
38+
*/
39+
fun topKFrequent01(nums: IntArray, k: Int): IntArray {
40+
val map = mutableMapOf<Int, Int>()
41+
for(num in nums) {
42+
map[num] = map.getOrDefault(num, 0) + 1
43+
}
44+
45+
// count List 초기화
46+
// map의 value는 nums Size를 넘을 수 없음.
47+
val countList = Array(nums.size + 1) { mutableListOf<Int>() }
48+
for ((key, value) in map) {
49+
countList[value].add(key)
50+
}
51+
52+
val result = mutableListOf<Int>()
53+
for (i in countList.size - 1 downTo 0) {
54+
for (num in countList[i]) {
55+
result.add(num)
56+
if (result.size == k) {
57+
return result.toIntArray()
58+
}
59+
}
60+
}
61+
return result.toIntArray()
62+
}

0 commit comments

Comments
 (0)