【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)
 */
相关推荐
xindafu26 分钟前
代码随想录算法训练营第五十天|图论part1
c语言·算法·图论
满分观察网友z1 小时前
从选择困难到最优策略:我如何用DP搞定“鱼和熊掌兼得”的排程难题(1751. 最多可以参加的会议数目 II)
后端·算法
满分观察网友z1 小时前
从一团乱麻到井然有序:我的海量任务调度“秘密武器”( 1353. 最多可以参加的会议数目)
算法
m0_535064601 小时前
C++类模版与友元
java·c++·算法
满分观察网友z2 小时前
从“最短响应路径”到二叉树最小深度:一个Bug引发的BFS探险之旅(111. 二叉树的最小深度)
后端·算法
阿里云大数据AI技术2 小时前
Post-Training on PAI (4):模型微调SFT、DPO、GRPO
人工智能·算法·云计算
CoovallyAIHub2 小时前
卷积网络到底能不能“定位”?一次对空间表示能力的深度解析
深度学习·算法·计算机视觉
用户40315986396632 小时前
和谐程序组
java·算法
用户40315986396632 小时前
缓存优化模拟
java·算法
用户40315986396632 小时前
遥控小车
java·算法