Skip to content

Commit a608b72

Browse files
authored
Create Top K Frequent Elements
1 parent 040c6d2 commit a608b72

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Top K Frequent Elements

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public int[] topKFrequent(int[] nums, int k) {
3+
Map<Integer, Integer> map = new HashMap<>();
4+
for(int i = 0; i<nums.length; i++){
5+
map.put(nums[i], map.getOrDefault(nums[i], 0)+1);
6+
}
7+
int[][] toS = new int[map.size()][2];
8+
int count = 0;
9+
Iterator hmIterator = map.entrySet().iterator();
10+
while (hmIterator.hasNext()) {
11+
Map.Entry mapElement = (Map.Entry)hmIterator.next();
12+
toS[count][0] = (int)mapElement.getKey();
13+
toS[count++][1] = (int)mapElement.getValue();
14+
}
15+
Arrays.sort(toS, new Comparator<int[]>(){
16+
public int compare(int[] o1, int[] o2){
17+
return o1[1] - o2[1];
18+
}
19+
});
20+
int[] res = new int[k];
21+
int ix = 0;
22+
for(int i = toS.length-1; i>=toS.length-k; i--){
23+
res[ix++] = toS[i][0];
24+
}
25+
return res;
26+
}
27+
}

0 commit comments

Comments
 (0)