classSolution{publicint[]topKFrequent(int[] nums,int k){int[] result =newint[k];HashMap<Integer,Integer> map =newHashMap<>();for(int i =0; i < nums.length; i++){int frequency = map.getOrDefault(nums[i],0)+1;
map.put(nums[i], frequency);}List<Integer> list =newLinkedList<Integer>(map.keySet());Collections.sort(list,newComparator<Integer>(){@Overridepublicintcompare(Integer o1,Integer o2){// TODO Auto-generated method stubreturn map.get(o2)- map.get(o1);}});for(int i =0; i < k; i++){
result[i]= list.get(i);}return result;}}
347.前K个高频元素思路:使用HashMap存储元素以及元素出现的频率使用List存储元素,再使用Collections对list按照自己的比较逻辑进行排序最后根据K值,保存到数组中返回即可代码实现class Solution { public int[] topKFrequent(int[] nums, int k) { int[] result = new int[k]; HashMap<Integer, Integer> map = new HashMap