【LeetCode 0703】【设计】【优先队列】返回数据流中第K大的元素

  1. Kth Largest Element in a Stream

Design a class to find the k^th largest element in a stream. Note that it is the k^th largest element in the sorted order, not the k^th distinct element.

Implement KthLargest class:

  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • int add(int val) Appends the integer val to the stream and returns the element representing the k^th largest element in the stream.

Example 1:

复制代码
**Input**
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
**Output**
[null, 4, 5, 5, 8, 8]

**Explanation**
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

Constraints:

  • 1 <= k <= 10^4
  • 0 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • -10^4 <= val <= 10^4
  • At most 10^4 calls will be made to add.
  • It is guaranteed that there will be at least k elements in the array when you search for the k^th element.
Idea
text 复制代码
1.基于数组实现/维护一个大小size=k的小堆
2.具体处理
当读入的元素个数不大于k个,直接入堆
当读入元素超过k个,则比较堆顶元素是否比下一个读入数要小
* 如果读入的元素比堆顶元素小,则忽略
* 反之,将读入的元素入堆,并调整/挤掉堆顶元素
最后堆顶元素即为第K大的元素
JavaScript Solution
javascript 复制代码
/**
 * @param {number} k
 * @param {number[]} nums
 */
var KthLargest = function(k, nums) {
    
};

/** 
 * @param {number} val
 * @return {number}
 */
KthLargest.prototype.add = function(val) {
    
};

/** 
 * Your KthLargest object will be instantiated and called as such:
 * var obj = new KthLargest(k, nums)
 * var param_1 = obj.add(val)
 */
相关推荐
小宋10219 分钟前
一套服务托管多个 LoRA:适配器加载、租户隔离与热切换实战
大数据·人工智能·算法
Rosanci18 分钟前
Codex 下载与本地部署实战:从安装到运行全流程指南
开发语言·前端·算法·chatgpt·codex
2401_8322981019 分钟前
人工智能时代的变革机遇与社会发展新格局
人工智能·职场和发展
我爱工作&工作love我27 分钟前
P14358 [CSP-J 2025] 座位
算法
旖旎夜光28 分钟前
LeetCode 1576: 替换所有的问号(模拟) —— 题解
c++·学习·算法·leetcode·力控
朝朝辞暮i30 分钟前
C++ 第 38 课:线程、SingleThreadedExecutor、MultiThreadedExecutor、Callback Group
开发语言·c++·算法·ros2
(Charon)35 分钟前
【C++面试】互斥锁与读写锁:使用场景、实现原理与写饥饿问题
c++·算法
longlongzihan37 分钟前
回溯法详解:LeetCode 46. 全排列
算法·leetcode·回溯
秋名RG40 分钟前
时间复杂度、空间复杂度与算法稳定性详解
数据结构·算法·排序算法
白色的北极熊1 小时前
c语言 求余运算符
c语言·数据结构·算法