【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)
 */
相关推荐
FPGA信号处理6 分钟前
【 凸优化】第六讲:求解器与支持向量机
算法·机器学习·支持向量机
专注仿真8 分钟前
支持向量机(SVM)算法详解与代码实例
算法·机器学习·支持向量机
Pniubi12 分钟前
力扣42接雨水(动态规划法)
算法·leetcode·职场和发展
weixin_3077791321 分钟前
RAG 级联失效分析——面试中的错误归因艺术
人工智能·python·面试·职场和发展
CQU_JIAKE27 分钟前
10.31[A]
算法·深度优先
zwc321043205531 分钟前
Day 5:threshold与inRange阈值分割
c++·图像处理·人工智能·opencv·算法·计算机视觉
云-缩影34 分钟前
实际项目中怎么选排序算法:从面试题到工程落地
java·算法·排序算法
Pniubi1 小时前
力扣46全排列(回溯(递归))
算法·leetcode·职场和发展
文丑颜不良啊2 小时前
LeetCode1461~1480题目解析
java·leetcode
ZhengEnCi10 小时前
Agent 架构怎么选:从单 Agent 到多 Agent 编排的选型决策指南
算法·架构