力扣hot100 前 K 个高频元素 小根堆 流 IntStream

Problem: 347. 前 K 个高频元素

文章目录

思路

👨‍🏫 参考

  • 小根堆(维护k个高频元素)
  • 遍历所有元素,当前堆大小 < k 或者 当前元素出现次数大于堆顶元素出现次数:替换掉堆顶元素

复杂度

⏰ 时间复杂度: O ( n log ⁡ k ) O(n\log{k}) O(nlogk)

🌎 空间复杂度: O ( n ) O(n) O(n)

Code

Java 复制代码
class Solution {
	public int[] topKFrequent(int[] nums, int k)
	{
//		将一个数组(nums)转换为一个 Map 对象,并计算数组中每个元素出现的次数。                       键            值         键冲突处理方案
		Map<Integer, Integer> map = IntStream.of(nums).boxed().collect(Collectors.toMap(e -> e, e -> 1, Integer::sum));
		PriorityQueue<Integer> heap = new PriorityQueue<>((o1, o2) -> {
			return map.get(o1) - map.get(o2);
		});// 存的是元素的值(只存 k 个最高频的元素)
		for (Integer x : map.keySet())
		{
			if (heap.size() < k)
				heap.add(x);
			else if (map.get(x) > map.get(heap.peek()))
			{
				heap.remove();//去掉最小的
				heap.add(x);//把较大的值加进去
			}
		}
		int[] res = new int[k];
		int idx = 0;
		while (!heap.isEmpty())
			res[idx++] = heap.poll();
		return res;
	}
}
相关推荐
jarenyVO9 分钟前
RabbitMQ全面学习指南
数据库·学习·rabbitmq
qq_534452529 分钟前
【算法 day02】LeetCode 209.长度最小的子数组 | 59.螺旋矩阵II
java·算法·leetcode·职场和发展
dying_man12 分钟前
LeetCode--31.下一个排列
算法·leetcode
桑晒.13 分钟前
系统入侵排查实战指南:从Windows到Linux的应急响应与溯源分析
linux·运维·windows
IC 见路不走18 分钟前
LeetCode 第75题:颜色分类
数据结构·算法·leetcode
Navigator_Z31 分钟前
LeetCode //C - 757. Set Intersection Size At Least Two
c语言·算法·leetcode
loriloy33 分钟前
数据库资源帖
数据库
dragon_perfect2 小时前
adoc(asciidoc)转为markdown的方法,把.adoc文件转换为markdown格式
linux·运维·deepseek本地知识库
fengye2071612 小时前
板凳-------Mysql cookbook学习 (十--7)
数据库·学习·mysql
RestCloud2 小时前
ETLCloud中数据生成规则使用技巧
大数据·服务器·数据库·etl·数字化转型·数据处理·集成平台