-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFrequentElements.java
More file actions
41 lines (25 loc) · 838 Bytes
/
Copy pathFrequentElements.java
File metadata and controls
41 lines (25 loc) · 838 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public int[] topKFrequent(int[] nums, int k) {
if (nums.length == k) {
return nums;
}
Map<Integer, Integer> freq = new HashMap<>();
int[] output = new int[k];
//fill the frequencies
for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
// init heap 'the less frequent element first
Queue<Integer> heap = new PriorityQueue<>(
(n1, n2) -> freq.get(n1)- freq.get(n2));
for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
int key = entry.getKey();
heap.add(key);
if (heap.size() > k ) heap.poll();
}
for (int i = k -1; i >=0 ; i--) {
output[i] = heap.poll();
}
return output;
}
}