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
| class Solution { public int[] topKFrequent(int[] nums, int k) { int[] ans = new int[k]; HashMap<Integer, Integer> map = new HashMap<>(); for (int num : nums) { map.put(num, map.getOrDefault(num, 0) + 1); } List<Map.Entry<Integer, Integer>> list = new ArrayList(map.entrySet()); list.sort(new Comparator<Map.Entry<Integer, Integer>>() { @Override public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return o2.getValue().compareTo(o1.getValue()); } }); for (int i = 0; i < k; i++) { ans[i] = list.get(i).getKey(); } return ans; } }
|