剑指 Offer II 059. 数据流的第 K 大数值

embedded/2025/3/6 6:35:18/

comments: true
edit_url: https://github.com/doocs/leetcode/edit/main/lcof2/%E5%89%91%E6%8C%87%20Offer%20II%20059.%20%E6%95%B0%E6%8D%AE%E6%B5%81%E7%9A%84%E7%AC%AC%20K%20%E5%A4%A7%E6%95%B0%E5%80%BC/README.md

剑指 Offer II 059. 数据流的第 K 大数值

题目描述

设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。

请实现 KthLargest 类:

  • KthLargest(int k, int[] nums) 使用整数 k 和整数流 nums 初始化对象。
  • int add(int val)val 插入数据流 nums 后,返回当前数据流中第 k 大的元素。

 

示例:

输入:
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
输出:
[null, 4, 5, 5, 8, 8]解释:
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3);   // return 4
kthLargest.add(5);   // return 5
kthLargest.add(10);  // return 5
kthLargest.add(9);   // return 8
kthLargest.add(4);   // return 8

 

提示:

  • 1 <= k <= 104
  • 0 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • -104 <= val <= 104
  • 最多调用 add 方法 104
  • 题目数据保证,在查找第 k 大元素时,数组中至少有 k 个元素

 

注意:本题与主站 703 题相同: https://leetcode.cn/problems/kth-largest-element-in-a-stream/

解法

方法一

Python3
import heapq as hp
class KthLargest:def __init__(self, k: int, nums: List[int]):self.lst=[]self.k=kfor n in nums:self.add(n)        def add(self, val: int) -> int:hp.heappush(self.lst,val)if len(self.lst)>self.k:hp.heappop(self.lst)return self.lst[0]        # Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
Java
class KthLargest {private PriorityQueue<Integer> q;private int size;public KthLargest(int k, int[] nums) {q = new PriorityQueue<>(k);size = k;for (int num : nums) {add(num);}}public int add(int val) {q.offer(val);if (q.size() > size) {q.poll();}return q.peek();}
}/*** Your KthLargest object will be instantiated and called as such:* KthLargest obj = new KthLargest(k, nums);* int param_1 = obj.add(val);*/
C++
class KthLargest {
public:priority_queue<int, vector<int>, greater<int>> q;int size;KthLargest(int k, vector<int>& nums) {size = k;for (int num : nums) add(num);}int add(int val) {q.push(val);if (q.size() > size) q.pop();return q.top();}
};/*** Your KthLargest object will be instantiated and called as such:* KthLargest* obj = new KthLargest(k, nums);* int param_1 = obj->add(val);*/
Go
type KthLargest struct {h *IntHeapk int
}func Constructor(k int, nums []int) KthLargest {h := &IntHeap{}heap.Init(h)for _, v := range nums {heap.Push(h, v)}for h.Len() > k {heap.Pop(h)}return KthLargest{h: h,k: k,}
}func (this *KthLargest) Add(val int) int {heap.Push(this.h, val)for this.h.Len() > this.k {heap.Pop(this.h)}return this.h.Top()
}func connectSticks(sticks []int) int {h := IntHeap(sticks)heap.Init(&h)res := 0for h.Len() > 1 {val := heap.Pop(&h).(int)val += heap.Pop(&h).(int)res += valheap.Push(&h, val)}return res
}type IntHeap []intfunc (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) {*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() any {old := *hn := len(old)x := old[n-1]*h = old[0 : n-1]return x
}func (h *IntHeap) Top() int {if (*h).Len() == 0 {return 0}return (*h)[0]
}/*** Your KthLargest object will be instantiated and called as such:* obj := Constructor(k, nums);* param_1 := obj.Add(val);*/
Swift
import Collectionsclass KthLargest {private var h: Heap<Int>private var size: Intinit(_ k: Int, _ nums: [Int]) {h = Heap()size = kfor x in nums {add(x)}}func add(_ val: Int) -> Int {h.insert(val)if h.count > size {h.removeMin()}return h.min!}
}/*** Your KthLargest object will be instantiated and called as such:* let obj = KthLargest(k, nums)* let ret_1: Int = obj.add(val)*/

http://www.ppmy.cn/embedded/170418.html

相关文章

JavaWeb XML

1、定义 EXtension markup language XML&#xff1a;可扩展自定义标记语言 2、XML的存在意义和用法 XML存在约束&#xff0c;可以自定义但也存在书写规则&#xff0c;一般不需要逐行书写。 我们使用XML&#xff0c;只需要基于第三方应用程序和已提供框架的配置文件进行修改…

SpringBoot项目集成ElasticSearch

1. 项目背景 处于失业找工作的阶段&#xff0c;随便写写吧~ 没啥背景&#xff0c;没啥意义&#xff0c;Java后端越来越卷了。第一学历不是本科&#xff0c;感觉真的是没有一点路可走。 如果有路过的小伙伴&#xff0c;如果身边还有坑位&#xff0c;不限第一学历的话&#xff0…

leetcode每日一题——1328. 破坏回文串

给你一个由小写英文字母组成的回文字符串 palindrome &#xff0c;请你将其中 一个 字符用任意小写英文字母替换&#xff0c;使得结果字符串的 字典序最小 &#xff0c;且 不是 回文串。 请你返回结果字符串。如果无法做到&#xff0c;则返回一个 空串 。 如果两个字符串长度…

leetcode1 两数之和 哈希表

什么时候使用哈希法&#xff0c;当我们需要查询一个元素是否出现过&#xff0c;或者一个元素是否在集合里的时候&#xff0c;就要第一时间想到哈希法。 242. 有效的字母异位词 (opens new window)这道题目是用数组作为哈希表来解决哈希问题&#xff0c;349. 两个数组的交集 (o…

Docker 学习(一)

一、Docker 核心概念 Docker 是一个开源的容器化平台&#xff0c;允许开发者将应用及其所有依赖&#xff08;代码、运行时、系统工具、库等&#xff09;打包成一个轻量级、可移植的“容器”&#xff0c;实现 “一次构建&#xff0c;随处运行”。 1、容器&#xff08;Container…

SpringBoot为什么要禁止循环依赖?

大家好&#xff0c;我是锋哥。今天分享关于【SpringBoot为什么要禁止循环依赖?】面试题。希望对大家有帮助&#xff1b; SpringBoot为什么要禁止循环依赖? 1000道 互联网大厂Java工程师 精选面试题-Java资源分享网 Spring Boot 和 Spring 框架之所以要避免循环依赖&#xf…

visual studio 2022中如何添加项目到解决方案中

在Visual Studio 2022中将现有项目添加到解决方案中&#xff0c;可按照以下步骤操作&#xff1a; ​打开解决方案资源管理器​ 在Visual Studio主界面中&#xff0c;通过菜单栏选择 ​视图 > 解决方案资源管理器&#xff0c;或直接使用快捷键打开该工具窗口。 ​右键添加现…

【长安大学】苹果手机/平板自动连接认证CHD-WIFI脚本(快捷指令)

背景&#xff1a; 前几天实在忍受不了CHD-WIFI动不动就断开&#xff0c;一天要重新连接&#xff0c;点登陆好几次。试了下在网上搜有没有CHD-WIFI的自动连接WIFI自动认证脚本&#xff0c;那样我就可以解放双手&#xff0c;随时用WIFI就行了&#xff0c;但是没有找到。于是我就…