【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)
 */
相关推荐
小O的算法实验室13 分钟前
2024年ESWA SCI1区TOP,基于自适应模糊惩罚的多约束无人机路径规划状态转移算法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
一条大祥脚19 分钟前
Codeforces Round 1072 (Div. 3) 树形背包|线段树二分|区间并查集维护区间合并/set维护区间分裂
算法·深度优先·图论
Xの哲學31 分钟前
Linux SKB: 深入解析网络包的灵魂
linux·服务器·网络·算法·边缘计算
无限进步_34 分钟前
【C语言&数据结构】二叉树遍历:从前序构建到中序输出
c语言·开发语言·数据结构·c++·算法·github·visual studio
CodeByV38 分钟前
【算法题】哈希
算法·哈希算法
独自破碎E41 分钟前
【层序遍历】序列化二叉树
leetcode
天赐学c语言44 分钟前
1.14 - 用栈实现队列 && 对模板的理解以及模板和虚函数区别
c++·算法·leecode
高洁0144 分钟前
AI智能体搭建(3)
人工智能·深度学习·算法·数据挖掘·知识图谱
不知名XL1 小时前
day24 贪心算法 part02
算法·贪心算法
AI科技星1 小时前
时空几何:张祥前统一场论20核心公式深度总结
人工智能·线性代数·算法·机器学习·生活