Skip to content

Commit a0f2bc0

Browse files
committed
Add Solution2.java to problems 0347
1 parent b70d69e commit a0f2bc0

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
3+
class Node {
4+
int key;
5+
int value;
6+
7+
public Node(int key, int value) {
8+
this.key = key;
9+
this.value = value;
10+
}
11+
}
12+
13+
public List<Integer> topKFrequent(int[] nums, int k) {
14+
Map<Integer, Integer> map = new HashMap<>();
15+
for (Integer num : nums) {
16+
Integer count = map.get(num);
17+
map.put(num, count == null ? 1 : count + 1);
18+
}
19+
20+
PriorityQueue<Node> queue = new PriorityQueue<>(k, new Comparator<Node>() {
21+
@Override
22+
public int compare(Node o1, Node o2) {
23+
return o2.value - o1.value;
24+
}
25+
});
26+
27+
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
28+
queue.offer(new Node(entry.getKey(), entry.getValue()));
29+
}
30+
31+
List<Integer> res = new ArrayList<>();
32+
while (k-- > 0) {
33+
res.add(queue.poll().key);
34+
}
35+
return res;
36+
}
37+
}

0 commit comments

Comments
 (0)