Skip to content

Commit 75fe80b

Browse files
committed
top-k-frequent-elements solution
1 parent 319db1e commit 75fe80b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.*;
2+
3+
4+
class Solution {
5+
/* 시간 복잡도: O(N + M * log k)
6+
* - for 루프: O(N), frequency 구하기
7+
* - for 루프: O(M * log k), Map 순회
8+
- Map 요소: M개
9+
* - PriorityQueue 연산 (offer, poll): 평균 O(logk)
10+
*
11+
* 공간 복잡도: O(N + k), HashMap에 n개 + PriorityQueue에 k개
12+
*/
13+
public int[] topKFrequent(int[] nums, int k) {
14+
Map<Integer, Integer> frequencyMap = new HashMap<>();
15+
// [num, frequency]
16+
PriorityQueue<int[]> minHeap = new PriorityQueue<>((o1, o2) -> {
17+
return o1[1] - o2[1];
18+
});
19+
for (int num : nums) {
20+
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
21+
}
22+
for (var entry: frequencyMap.entrySet()) {
23+
minHeap.add(new int[]{entry.getKey(), entry.getValue()});
24+
if (minHeap.size() > k) {
25+
minHeap.poll();
26+
}
27+
}
28+
29+
int[] answer = new int[k];
30+
for (int i = 0; i < k; i++) {
31+
answer[i] = minHeap.poll()[0];
32+
}
33+
return answer;
34+
}
35+
}
36+

0 commit comments

Comments
 (0)