序
本文次要记录一下leetcode哈希表之前K个高频元素
题目
给定一个非空的整数数组,返回其中呈现频率前 k 高的元素。 示例 1:输出: nums = [1,1,1,2,2,3], k = 2输入: [1,2]示例 2:输出: nums = [1], k = 1输入: [1] 提醒: 你能够假如给定的 k 总是正当的,且 1 ≤ k ≤ 数组中不雷同的元素的个数。 你的算法的工夫复杂度必须优于 O(n log n) , n 是数组的大小。 题目数据保障答案惟一,换句话说,数组中前 k 个高频元素的汇合是惟一的。 你能够按任意程序返回答案。起源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/top-k-frequent-elements著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
题解
class Solution { public int[] topKFrequent(int[] nums, int k) { if (nums == null || nums.length <= k) { return nums; } Map<Integer,Integer> countMap = new HashMap<>(); for (int num : nums) { countMap.put(num, countMap.getOrDefault(num, 0) + 1); } PriorityQueue<Integer> queue=new PriorityQueue<>(new Comparator<Integer> () { @Override public int compare(Integer o1, Integer o2) { return countMap.get(o1)-countMap.get(o2); } }); for (Map.Entry<Integer,Integer> entry : countMap.entrySet()) { if (queue.size() < k) { queue.add(entry.getKey()); continue; } if (countMap.get(queue.peek()) < entry.getValue()) { queue.poll(); queue.add(entry.getKey()); } } int[] result = new int[k]; for (int i = 0; i < k; ++i) { result[i] = queue.poll(); } return result; }}
小结
这里先借助HashMap来统计元素呈现的频次,而后再借助PriorityQueue来保护topK的元素,最初取出来topK元素转换为数组。
doc
- 前K个高频元素