-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d506bc7
commit 4ec90d0
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** | ||
* @param {number} k | ||
* @param {number[]} nums | ||
*/ | ||
/** | ||
* @param {number} val | ||
* @return {number} | ||
*/ | ||
class KthLargest { | ||
constructor(k, nums) { | ||
this.k = k; | ||
this.pq = new MinPriorityQueue(); | ||
|
||
for(let num of nums) { | ||
this.add(num) | ||
} | ||
} | ||
add(val) { | ||
if (this.pq.size() < this.k){ | ||
this.pq.enqueue(val); | ||
return this.pq.front().element | ||
} | ||
let min = this.pq.front().element; | ||
if (val > min){ | ||
this.pq.dequeue(); | ||
this.pq.enqueue(val); | ||
} | ||
return this.pq.front().element; | ||
} | ||
} | ||
|
||
/** | ||
* Your KthLargest object will be instantiated and called as such: | ||
* var obj = new KthLargest(k, nums) | ||
* var param_1 = obj.add(val) | ||
*/ | ||
|
||
// 2022/05/30 done. | ||
// Runtime: 231 ms, faster than 61.13% of JavaScript online submissions for Kth Largest Element in a Stream. | ||
// Memory Usage: 51.7 MB, less than 54.10% of JavaScript online submissions for Kth Largest Element in a Stream. |