Skip to content

Commit ecaff8c

Browse files
committed
solve top-k-frequent elements
1 parent d11d808 commit ecaff8c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
// return: top k most freq elements
5+
public int[] topKFrequent(int[] nums, int k) {
6+
HashMap<Integer, Integer> freq = new HashMap<>();
7+
// O (N)
8+
for(int num : nums) {
9+
freq.put(num, freq.getOrDefault(num, 0) + 1); // O(1)
10+
}
11+
12+
// O (N log k)
13+
PriorityQueue<int[]> heap = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
14+
for(int num : freq.keySet()) {
15+
int f = freq.get(num); // O(1)
16+
heap.add(new int[]{num, f}); // O(log k)
17+
18+
if(heap.size() > k) heap.poll(); // O(log k)
19+
}
20+
21+
// O (N log k)
22+
int[] result = new int[k];
23+
for(int i = 0; i < k; i++) {
24+
result[i] = heap.poll()[0]; // O(log k)
25+
}
26+
27+
return result;
28+
}
29+
}

0 commit comments

Comments
 (0)