数据流中的第K大元素
一、LeetCode题解
瞧一瞧~
- 博健的LeetCode题解:Gitbook版本传送门
- 博健的LeetCode题解:CSDN传送门
- 前端进阶笔记:Gitbook传送门
二、算法题
题目
设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。
你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,返回当前数据流中第K大的元素。
示例:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
解法一 (暴力比较)
思路
- 思路待总结
代码
var KthLargest = function (k, nums) {
this.data = nums
this.k = k
let len = this.data.length
let parent = Math.floor((len - 2) / 2)
this.shiftDown = function (k) {
while (k * 2 + 1 < this.data.length) {
let j = k * 2 + 1
if (k * 2 + 2 < this.data.length && this.data[j] > this.data[j + 1]) {
j += 1
}
if (this.data[k] > this.data[j]) {
let m = this.data[k]
this.data[k] = this.data[j]
this.data[j] = m
k = j
} else {
break
}
}
}
this.shiftUp = function (k) {
while (k > 0) {
let parent = Math.floor((k - 1) / 2)
if (this.data[parent] > this.data[k]) {
let m = this.data[k]
this.data[k] = this.data[parent]
this.data[parent] = m
k = parent
} else {
break
}
}
}
this.extracMin = function () {
this.data[0] = this.data[this.data.length - 1]
this.data.pop()
this.shiftDown(0)
}
for (parent; parent >= 0; parent--) {
this.shiftDown(parent)
}
while (this.data.length > k) {
this.extracMin()
}
};
KthLargest.prototype.add = function (val) {
if (this.data.length < this.k) {
this.data.push(val)
this.shiftUp(this.data.length - 1)
} else {
if (val > this.data[0]) {
this.data[0] = val
this.shiftDown(0)
}
}
return this.data[0]
};