Skip to content

Commit b30a901

Browse files
committed
top k frequent elements solution
1 parent e3ec04c commit b30a901

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
[문제풀이]
3+
time: O(N log N), space: O(N + k)
4+
- 주어진 Nums의 중복된 수의 갯수를 Map에 담고,
5+
- 역정렬하면,
6+
- k만큼 뽑기
7+
class Solution1 {
8+
public int[] topKFrequent(int[] nums, int k) {
9+
Map<Integer, Integer> counting = new HashMap<>();
10+
for (int num: nums) {
11+
int numCount = counting.getOrDefault(num, 0) + 1;
12+
counting.put(num, numCount);
13+
}
14+
15+
List<Map.Entry<Integer, Integer>> sortedCounting = new ArrayList<>(counting.entrySet());
16+
sortedCounting.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
17+
18+
int[] result = new int[k];
19+
for (int i = 0; i < k; i++) {
20+
result[i] = sortedCounting.get(i).getKey();
21+
}
22+
23+
return result;
24+
}
25+
}
26+
27+
time: O(N log k), space: O(N + k)
28+
- PriorityQueue 사용
29+
- value로 역정렬 설정
30+
- key로 queue에 add
31+
32+
[회고]
33+
첫번째 풀이는 역정렬 하는 부분이 미숙했고,
34+
두번째 풀이는 PriorityQueue를 사용하는데 처음 써본다.. (익히자!)
35+
*/
36+
class Solution {
37+
public int[] topKFrequent(int[] nums, int k) {
38+
Map<Integer, Integer> counting = new HashMap<>();
39+
for (int num: nums) {
40+
int numCount = counting.getOrDefault(num, 0) + 1;
41+
counting.put(num, numCount);
42+
}
43+
44+
Queue<Integer> queue = new PriorityQueue<>((count1, count2) ->
45+
counting.get(count2) - counting.get(count1));
46+
queue.addAll(counting.keySet());
47+
48+
int[] result = new int[k];
49+
for (int i = 0; i < k; i++) {
50+
result[i] = queue.poll();
51+
}
52+
return result;
53+
}
54+
}

0 commit comments

Comments
 (0)