方法1: 声明新的类 + hashmap + priority queue
1 class Solution { 2 public ListtopKFrequent(int[] array, int k) { 3 Queue queue = new PriorityQueue (newComparator); 4 Map 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 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 newComparator = new Comparator () {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 }