Skip to content

Commit c1045c8

Browse files
committed
Top k frequent elements solved
1 parent 0a4aa77 commit c1045c8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
public int[] topKFrequent(int[] nums, int k) {
5+
Map<Integer,Integer> counts = new HashMap<>();
6+
List<Integer> ordering = new ArrayList<>();
7+
int[] results = new int[k];
8+
9+
for(int n : nums){
10+
if(counts.containsKey(n)){
11+
counts.put(n, counts.get(n)+1);
12+
continue;
13+
}
14+
counts.put(n, 1);
15+
ordering.add(n);
16+
}
17+
18+
ordering.sort((o1,o2) -> counts.get(o2) - counts.get(o1));
19+
for(int i = 0; i < k; i++){
20+
results[i] = ordering.get(i);
21+
}
22+
23+
return results;
24+
}
25+
}
26+

0 commit comments

Comments
 (0)