diff --git a/solution/0700-0799/0703.Kth Largest Element in a Stream/README.md b/solution/0700-0799/0703.Kth Largest Element in a Stream/README.md index a3bfc1571e398..15c9606146997 100644 --- a/solution/0700-0799/0703.Kth Largest Element in a Stream/README.md +++ b/solution/0700-0799/0703.Kth Largest Element in a Stream/README.md @@ -349,6 +349,39 @@ class MinHeap { */ ``` +#### TypeScript + +```ts +class KthLargest { + #pq = new MinPriorityQueue(); + #k = 0; + + constructor(k: number, nums: number[]) { + this.#k = k; + for (const x of nums) { + this.#pq.enqueue(x); + if (this.#pq.size() > k) { + this.#pq.dequeue(); + } + } + } + + add(val: number): number { + this.#pq.enqueue(val); + if (this.#pq.size() > this.#k) { + this.#pq.dequeue(); + } + 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) + */ +``` + diff --git a/solution/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md b/solution/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md index 731b7c4eaa78f..254d1a356e5a1 100644 --- a/solution/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md +++ b/solution/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md @@ -348,6 +348,39 @@ class MinHeap { */ ``` +#### TypeScript + +```ts +class KthLargest { + #pq = new MinPriorityQueue(); + #k = 0; + + constructor(k: number, nums: number[]) { + this.#k = k; + for (const x of nums) { + this.#pq.enqueue(x); + if (this.#pq.size() > k) { + this.#pq.dequeue(); + } + } + } + + add(val: number): number { + this.#pq.enqueue(val); + if (this.#pq.size() > this.#k) { + this.#pq.dequeue(); + } + 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) + */ +``` + diff --git a/solution/0700-0799/0703.Kth Largest Element in a Stream/Solution.ts b/solution/0700-0799/0703.Kth Largest Element in a Stream/Solution.ts new file mode 100644 index 0000000000000..31a43e43c589c --- /dev/null +++ b/solution/0700-0799/0703.Kth Largest Element in a Stream/Solution.ts @@ -0,0 +1,28 @@ +class KthLargest { + #pq = new MinPriorityQueue(); + #k = 0; + + constructor(k: number, nums: number[]) { + this.#k = k; + for (const x of nums) { + this.#pq.enqueue(x); + if (this.#pq.size() > k) { + this.#pq.dequeue(); + } + } + } + + add(val: number): number { + this.#pq.enqueue(val); + if (this.#pq.size() > this.#k) { + this.#pq.dequeue(); + } + 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) + */