Kth Largest Element in a Stream LeetCode solution in JavaScript

1
var KthLargest = function (k, nums) {
2
// sort ascending because I am familiar with it
3
// when applying my binary search algorithm
4
this.nums = nums.sort((a, b) => a - b);
5
this.k = k;
6
};
7

8
KthLargest.prototype.add = function (val) {
9
// search a place to push val
10
// using binary search
11
let left = 0;
12
right = this.nums.length - 1;
13
while (left < right) {
14
let mid = left + Math.floor((right + 1 - left) / 2);
15

16
if (val < this.nums[mid]) {
17
right = mid - 1;
18
} else {
19
left = mid;
20
}
21
}
22

23
// push val into the nums
24
this.nums.splice(left + (this.nums[left] < val ? 1 : 0), 0, val);
25

26
// because our nums is sorted
27
// so kth largest element is easy to be returned
28
return this.nums[this.nums.length - this.k];
29
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0