【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)
 */
相关推荐
炼金士2 分钟前
客户导向型IT服务项目绩效测量的双仪表盘治理模型研究——基于责任边界与行为防御的视角
职场和发展
一切皆是因缘际会26 分钟前
资源的适配
大数据·人工智能·算法
鲸能云29 分钟前
【智慧能源】源储调售一体化架构与 EMS 滚动调度算法实践 —— 工商业光储收益提升 22% 的技术拆解
算法·架构·能源
双翌视觉37 分钟前
曝光调不对,算法全白费:机器视觉的曝光三态解析
人工智能·算法·计算机视觉
ysu_03141 小时前
02-单链表完全指南
c语言·数据结构·算法·leetcode
生态学者1 小时前
香港理工大学Nature Communications:沿海塑料际古菌组特征及生态影响
大数据·人工智能·算法·r语言·微信公众平台
ocean21031 小时前
2025-2026年计算机网络面试高频知识点洞察
计算机网络·面试·职场和发展·https·tcp·面试真题·秋招春招
圣保罗的大教堂1 小时前
leetcode 3904. 最小稳定下标 II 中等
leetcode
ly-272531 小时前
IEEE PDF eXpress终稿检测踩坑记录:PDF图片字体未嵌入与LaTeX参考文献编译异常解决方法
服务器·人工智能·算法
代码不停1 小时前
子序列问题
java·算法