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
| class Solution { public int[] topKFrequent(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length ; i++) { if (map.containsKey(nums[i])){ map.put(nums[i], map.get(nums[i]) + 1); }else { map.put(nums[i], 1); } }
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(k, 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 (Map.Entry<Integer, Integer> entry : map.entrySet()){ queue.add(entry); }
int[] result = new int[k]; for (int i = 0; i < k ; i++) { result[i] = queue.poll().getKey(); } return result; } }
|