-
Notifications
You must be signed in to change notification settings - Fork 1
/
TopKFrequentElements.java
42 lines (36 loc) · 1.09 KB
/
TopKFrequentElements.java
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
42
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.*;
// https://leetcode.com/problems/top-k-frequent-elements/
public class TopKFrequentElements {
private final int[] nums;
private final int k;
public TopKFrequentElements(int[] nums, int k) {
this.nums = nums;
this.k = k;
}
public int[] solution() {
Map<Integer, Integer> values = new HashMap<>();
for (int num : nums) {
int count = 1;
if (values.containsKey(num)) {
count = values.get(num);
}
values.put(num, ++count);
}
Queue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(
Comparator.comparingInt(Map.Entry::getValue)
);
for (var entry : values.entrySet()) {
queue.add(entry);
if (queue.size() > k) {
queue.remove();
}
}
int[] result = new int[k];
int i = 0;
while (!queue.isEmpty()) {
result[i++] = queue.remove().getKey();
}
return result;
}
}