-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathTopK.java
42 lines (40 loc) · 1.11 KB
/
TopK.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
/*https://practice.geeksforgeeks.org/problems/top-k-frequent-elements-in-array/1*/
class Pair implements Comparable<Pair>
{
int val;
int count;
Pair(int v, int c)
{
val = v;
count = c;
}
public int compareTo(Pair p)
{
if (this.count > p.count) return -1;
if (this.count < p.count) return 1;
return p.val-this.val;
}
}
class Solution {
public int[] topK(int[] nums, int k) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for (Integer num : nums)
{
if (map.containsKey(num))
map.put(num,map.get(num)+1);
else
map.put(num,1);
}
PriorityQueue<Pair> pq = new PriorityQueue<Pair>();
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
Map.Entry elem = (Map.Entry)it.next();
pq.add(new Pair((Integer)elem.getKey(), (Integer)elem.getValue()));
}
int[] result = new int[k];
for (int i = 0; i < k; ++i)
result[i] = pq.poll().val;
return result;
}
}