-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path347_top_k_frequent_elements.java
More file actions
35 lines (28 loc) · 949 Bytes
/
Copy path347_top_k_frequent_elements.java
File metadata and controls
35 lines (28 loc) · 949 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
class Node {
int key;
int val;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0)
return res;
Map<Integer, Integer> dict = new HashMap<>();
for (int num : nums)
dict.put(num, dict.getOrDefault(num, 0) + 1);
PriorityQueue<Node> queue = new PriorityQueue<>(new Comparator<Node>() {
public int compare(Node n1, Node n2) {
return n2.val - n1.val;
}
});
for (Map.Entry<Integer, Integer> entry : dict.entrySet())
queue.add(new Node(entry.getKey(), entry.getValue()));
for (int i = 0; i < k; i++)
res.add(queue.poll().key);
return res;
}
}