import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param k int整型 * @return int整型一维数组 */ public int[] most_popular_cows (int[] nums, int k) { HashMap<Integer, Integer> hashMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { hashMap.put(nums[i], hashMap.getOrDefault(nums[i], 0) + 1); } PriorityQueue<Map.Entry<Integer,Integer>> priorityQueue = new PriorityQueue<>((o1, o2) -> { Integer value1 = o1.getValue(); Integer value2 = o2.getValue(); return value2 - value1; }); Set<Map.Entry<Integer, Integer>> entries = hashMap.entrySet(); priorityQueue.addAll(entries); int index = 0; int [] result = new int [k]; while(index<k&&!priorityQueue.isEmpty()){ Map.Entry<Integer,Integer> entry = priorityQueue.poll(); Integer key = entry.getKey(); result[index++] = key; } Arrays.sort(result); return result; } }
本题知识点分析:
1.哈希表
2.优先级队列(最小堆排序)
3.哈希存取
4.数学模拟
5.API函数(Arrays.sort)
本题解题思路分析:
1.先记录每个数字和它们出现次数,放入到hashMap中
2.创建一个优先级队列存放hashMap的entry接口,存key和value
3.自定义排序,以value为降序
4.将哈希map所有entry放入优先级队列
5.然后就是出队操作,出k个,取key,然后按升序进行排序返回
本题:可以做一下优化,先放入优先级队列时,采用增加for循环,每次去判断如果队列大小大于k,说明要进行出队操作,因为我们只要前k出现频率最多的数字,其他都是冗余的。
本题使用编程语言: Java
如果你觉得本篇文章对你有帮助的话,可以点个赞支持一下,感谢~