703. 数据流中的第 K 大元素
设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。
请实现 KthLargest 类:
KthLargest(int k, int[] nums) 使用整数 k 和整数流 nums 初始化对象。
int add(int val) 将 val 插入数据流 nums 后,返回当前数据流中第 k 大的元素。
示例:
输入:
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
输出:
[null, 4, 5, 5, 8, 8]
解释:
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
方法分析
这道题有两种思路
-
数组 一种是维护一个数组,保存前K大值,sort排序,排序用快排,所以最后时间复杂度为
-
优先队列 另一种是维护一个优先队列,维护一个MinHeap,优先级从小到大排列,保证
size=k时间复杂度, 平均 -
结果比较 复杂度由 klogk --> logk 下降了k倍。
实现一个小顶堆
class MinHeap {
constructor (data = []) {
this.data = data;
this.heapify();
}
heapify() {
for (let i = 1; i < this.size(); i++) {
this.bubbleUp(i);
}
}
bubbleUp(index) {
while (index > 0) {
const parentIndex = (index - 1) >> 1;
if (this.comparator(index, parentIndex) < 0) {
this.swap(index, parentIndex);
index = parentIndex
} else {
break;
}
}
}
bubbleDown(index) {
while (true) {
const leftIndex = index * 2 + 1;
const rightIndex = index * 2 + 2;
let findIndex = index;
if (this.comparator(leftIndex, findIndex) < 0) {
findIndex = leftIndex;
}
if (this.comparator(rightIndex, findIndex) < 0) {
findIndex = rightIndex;
}
if (findIndex !== index) {
this.swap(index, findIndex);
index = findIndex;
} else {
break;
}
}
}
offer(value) {
this.data.push(value);
this.bubbleUp(this.size() - 1);
}
comparator(a, b) {
return this.data[a] - this.data[b];
}
swap(a, b) {
[this.data[a], this.data[b]] = [this.data[b], this.data[a]]
}
size() {
return this.data.length;
}
/**
* @description: 返回堆顶元素,不改变堆
* @param {*}
* @return {*}
*/
peek() {
if (this.size() === 0) return null;
return this.data[0];
}
poll() {
if (this.size() === 0) return null;
const first = this.data[0];
const last = this.data.pop();
if (this.size() > 0) {
this.data[0] = last;
this.bubbleDown(0);
}
return first;
}
}
// const data = [3,6,1,2,5];
// const minHeap = new Minheap(data);
// minHeap.offer(4);
// console.log(minHeap);
// minHeap.poll();
// console.log(minHeap);
var KthLargest = function(k, nums) {
this.k = k;
this.minHeap = new MinHeap();
for (const i of nums) {
this.add(i);
}
};
KthLargest.prototype.add = function(val) {
this.minHeap.offer(val);
if (this.minHeap.size() > this.k) {
this.minHeap.poll();
}
return this.minHeap.peek();
};
const kth = new KthLargest(3, [3,6,1,2,5]);
console.log(kth.add(4));
console.log(kth.add(10));
console.log(kth.add(7));