File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments