题目链接:
https://leetcode-cn.com/problems/top-k-frequent-elements/
解题思路:
多了一个hashmap的排序
1 class Solution { 2 public List<Integer> topKFrequent(int[] nums, int k) { 3 4 Map<Integer,Integer> freqMap = new HashMap<>(); 5 6 for(int i=0;i<nums.length;i++) 7 { 8 if(freqMap.containsKey(nums[i])) 9 { 10 int count = freqMap.get(nums[i]); 11 12 freqMap.put(nums[i],++count); 13 } 14 else 15 { 16 freqMap.put(nums[i],1); 17 } 18 } 19 20 List<Map.Entry<Integer, Integer>> list = new ArrayList<>(freqMap.entrySet()); 21 Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() { 22 @Override 23 public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { 24 return o2.getValue() - o1.getValue(); 25 } 26 }); 27 28 int X=0; 29 List<Integer> ret = new ArrayList<>(); 30 for (Map.Entry<Integer, Integer> entry : list) { 31 ret.add(entry.getKey()); 32 ++X; 33 if (X >= k) { 34 break; 35 } 36 } 37 return ret; 38 39 } 40 }