Skip to content

Commit 4388995

Browse files
committed
Solution for Top K Frequent Elements #237
1 parent 1041629 commit 4388995

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
import java.util.PriorityQueue;
4+
import java.util.Comparator;
5+
6+
public class dohyeon2 {
7+
public int[] topKFrequent(int[] nums, int k) {
8+
// approach :
9+
// 1. create map to match num to frequency
10+
// 2. create max frequency Priority Queue for sort
11+
// 3. pop the max value from the queue until k
12+
// time complexity O(n log n) : priority queue comparison
13+
// space complexity O(n)
14+
15+
// ChatGPT says that there is O(n) solution for this, how?
16+
HashMap<Integer, Integer> frequentMap = new HashMap<>();
17+
18+
for (int i = 0; i < nums.length; i++) {
19+
int num = nums[i];
20+
frequentMap.merge(num, 1, Integer::sum);
21+
}
22+
23+
PriorityQueue<Map.Entry<Integer, Integer>> PQ = new PriorityQueue<>(k,
24+
Comparator.comparing(Map.Entry<Integer, Integer>::getValue).reversed());
25+
26+
for(Map.Entry<Integer,Integer> e : frequentMap.entrySet()){
27+
PQ.add(e);
28+
}
29+
30+
int[] result = new int[k];
31+
32+
int idx = 0;
33+
34+
while (idx < k && PQ.size() > 0) {
35+
Map.Entry<Integer, Integer> v = PQ.poll();
36+
result[idx] = (int) v.getKey();
37+
idx++;
38+
}
39+
40+
return result;
41+
}
42+
}

0 commit comments

Comments
 (0)