方法1: 声明新的类 + hashmap + priority queue
1 class Solution { 2 public List<Integer> topKFrequent(int[] array, int k) { 3 Queue<Result> queue = new PriorityQueue<Result>(newComparator); 4 Map<Integer, Integer> map = new HashMap<>(); 5 for (int i = 0; i < array.length; i++) { 6 if (map.containsKey(array[i])) { 7 map.put(array[i], map.get(array[i]) + 1); 8 } else { 9 map.put(array[i], 1); 10 } 11 } 12 for(int i : map.keySet()) { 13 queue.offer(new Result(i, map.get(i))); 14 } 15 16 List<Integer> res = new ArrayList<>(); 17 for (int i = 0; i < k; i++) { 18 res.add(queue.poll().val); 19 } 20 return res; 21 } 22 23 public Comparator<Result> newComparator = new Comparator<Result>() { 24 public int compare(Result a, Result b) { 25 if (a.freq == b.freq) { 26 return 0; 27 } 28 //-1是倒向排序, 1是正向排序 29 return a.freq > b.freq ? -1 : 1; 30 } 31 }; 32 } 33 34 class Result { 35 int val, freq; 36 public Result(int val, int freq) { 37 this.val = val; 38 this.freq = freq; 39 } 40 }