diff --git a/README.md b/README.md index 5d15372..f8fe8b4 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ since 2021.10.10 / Benben - 0509.Fibonacci Number - 0543.Diameter of Binary Tree - 0572.Subtree of Another Tree +- 0703.Kth Largest Element in a Stream - 0704.Binary Search - 0905.Sort Array By Parity - 1694.Reformat Phone Number diff --git a/leetcode-easy/0703-kth-largest-element-in-a-stream.js b/leetcode-easy/0703-kth-largest-element-in-a-stream.js new file mode 100644 index 0000000..df20290 --- /dev/null +++ b/leetcode-easy/0703-kth-largest-element-in-a-stream.js @@ -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.