-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
37 lines (35 loc) · 936 Bytes
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* @param {number} k
* @param {number[]} nums
*/
var KthLargest = function(k, nums) {
let length = nums.length
this.heap = nums.sort((a, b) => a - b)
this.heap = this.heap.slice(length >= k ? length - k : 0)
this.length = k
};
/**
* @param {number} val
* @return {number}
*/
KthLargest.prototype.add = function(val) {
let heapLength = this.heap.length
if (heapLength < this.length || this.heap[0] < val) {
let i = 0,
length = Math.min(this.length, heapLength)
while (i < length) {
if (this.heap[i] >= val) {
break
}
i++
}
this.heap.splice(i, 0, val)
if (heapLength === this.length) this.heap.shift()
}
return this.heap[0]
};
/**
* Your KthLargest object will be instantiated and called as such:
* var obj = Object.create(KthLargest).createNew(k, nums)
* var param_1 = obj.add(val)
*/