Skip to content

Commit 62532ae

Browse files
committed
top k frequent elements
1 parent 3502dd4 commit 62532ae

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed
Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,32 @@
11
import java.util.HashMap;
22
import java.util.Map;
3+
import java.util.PriorityQueue;
4+
5+
// 시간 복잡도: O(nlogk) - 최대 힙에 k개의 요소를 넣는데 O(logk)가 걸리고, 이를 n번 반복
6+
// 공간 복잡도: O(n) - 빈도수를 저장하는 freqMap
37
class Solution {
4-
public static int[] topKFrequent(int[] nums, int k) {
5-
Map<Integer, Integer> myMap = new HashMap<>();
6-
for (int num : nums) {
7-
myMap.put(num, myMap.getOrDefault(num, 0) + 1);
8-
}
9-
return myMap.entrySet()
10-
.stream()
11-
.sorted((v1, v2) -> Integer.compare(v2.getValue(),v1.getValue()))
12-
.map(Map.Entry::getKey)
13-
.mapToInt(Integer::intValue)
14-
.toArray();
8+
9+
public int[] topKFrequent(int[] nums, int k) {
10+
Map<Integer, Integer> freqMap = new HashMap<>();
11+
for (int num : nums) {
12+
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
1513
}
14+
15+
PriorityQueue<Map.Entry<Integer, Integer>> maxHeap =
16+
new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
17+
18+
// 빈도수를 기준으로 최소 힙에 k개의 요소를 넣기
19+
for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
20+
maxHeap.offer(entry);
21+
}
22+
23+
int[] result = new int[k];
24+
int index = 0;
25+
while (k > 0) {
26+
k--;
27+
result[index++] = maxHeap.poll().getKey();
28+
}
29+
30+
return result;
31+
}
1632
}

0 commit comments

Comments
 (0)