From 162724ec530e7f0e4a4d9b6b127406a07d4c61f3 Mon Sep 17 00:00:00 2001 From: mt2324 <63892273+mt2324@users.noreply.github.com> Date: Fri, 11 Sep 2026 14:28:21 +0900 Subject: [PATCH] Create 703. Kth Largest Element in a Stream.md --- .../703. Kth Largest Element in a Stream.md | 137 ++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 703. Kth Largest Element in a Stream/703. Kth Largest Element in a Stream.md diff --git a/703. Kth Largest Element in a Stream/703. Kth Largest Element in a Stream.md b/703. Kth Largest Element in a Stream/703. Kth Largest Element in a Stream.md new file mode 100644 index 0000000..d7a0872 --- /dev/null +++ b/703. Kth Largest Element in a Stream/703. Kth Largest Element in a Stream.md @@ -0,0 +1,137 @@ +## Description +[703. Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) + +You are part of a university admissions office and need to keep track of the `kth` highest test score from applicants in real-time. This helps to determine cut-off marks for interviews and admissions dynamically as new applicants submit their scores. + +You are tasked to implement a class which, for a given integer `k`, maintains a stream of test scores and continuously returns the `k`th highest test score **after** a new score has been submitted. More specifically, we are looking for the `k`th highest score in the sorted list of all scores. + +Implement the `KthLargest` class: + +- `KthLargest(int k, int[] nums)` Initializes the object with the integer `k` and the stream of test scores `nums`. +- `int add(int val)` Adds a new test score `val` to the stream and returns the element representing the `kth` largest element in the pool of test scores so far. + +**Example 1:** + +**Input:** +["KthLargest", "add", "add", "add", "add", "add"] +[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] + +**Output:** [null, 4, 5, 5, 8, 8] + +**Explanation:** + +KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); +kthLargest.add(3); // return 4 +kthLargest.add(5); // return 5 +kthLargest.add(10); // return 5 +kthLargest.add(9); // return 8 +kthLargest.add(4); // return 8 + +**Example 2:** + +**Input:** +["KthLargest", "add", "add", "add", "add"] +[[4, [7, 7, 7, 7, 8, 3]], [2], [10], [9], [9]] + +**Output:** [null, 7, 7, 7, 8] + +**Explanation:** + +KthLargest kthLargest = new KthLargest(4, [7, 7, 7, 7, 8, 3]); +kthLargest.add(2); // return 7 +kthLargest.add(10); // return 7 +kthLargest.add(9); // return 7 +kthLargest.add(9); // return 8 + +**Constraints:** + +- `0 <= nums.length <= 104` +- `1 <= k <= nums.length + 1` +- `-104 <= nums[i] <= 104` +- `-104 <= val <= 104` +- At most `104` calls will be made to `add`. + + +## STEP1 +max heapにするのかと思ったけど、kの大きさのmin heapを用意しておけば先頭が必然的にk番目に大きい。 +```python +class KthLargest: + + def __init__(self, k: int, nums: List[int]): + self.k = k + self.heap = nums + heapq.heapify(self.heap) + while len(self.heap) > k: + heapq.heappop(self.heap) + + def add(self, val: int) -> int: + heapq.heappush(self.heap, val) + if len(self.heap) > self.k: + heapq.heappop(self.heap) + return self.heap[0] + + +# Your KthLargest object will be instantiated and called as such: +# obj = KthLargest(k, nums) +# param_1 = obj.add(val) +``` +## STEP 2 +ちょっと変数名が雑すぎるので改善。与えられたnumsは破壊しない方がいい。addの返り値が個人的には直感的でないので、commentを足しておく。 + +```python +class KthLargest: + + def __init__(self, k: int, nums: List[int]): + self.k = k + self.top_k_scores = nums.copy() + heapq.heapify(self.top_k_scores) + while len(self.top_k_scores) > k: + heapq.heappop(self.top_k_scores) + + ### Adds a new score to the heap which keeps top k elements and returns the new Kth Largest Element. + def add(self, val: int) -> int: + heapq.heappush(self.top_k_scores, val) + if len(self.top_k_scores) > self.k: + heapq.heappop(self.top_k_scores) + return self.top_k_scores[0] + + +# Your KthLargest object will be instantiated and called as such: +# obj = KthLargest(k, nums) +# param_1 = obj.add(val) +``` +https://docs.python.org/3.14/tutorial/datastructures.html +リストのcopyメソッドはshallow copyで + +https://docs.python.org/3.14/library/copy.html +copyモジュールにshallow copyのcopy()とdeepcopy()があることを確認。新しくreplace()という関数がリリースされており、dataclassとかnamedtupleで使える。shallow copyしつつ、一部を書き換える操作をしている。 + +dataclassってなんだっけと脱線 +https://docs.python.org/3/library/dataclasses.html + +## STEP 3 + +```python +import heapq +class KthLargest: + + def __init__(self, k: int, nums: List[int]): + self.k = k + self.top_k_scores = nums.copy() + heapq.heapify(self.top_k_scores) + while len(self.top_k_scores) > self.k: + heapq.heappop(self.top_k_scores) + + # Adds a new score to KthLargest and returns the new Kth Largest Element. + def add(self, val: int) -> int: + heapq.heappush(self.top_k_scores, val) + if len(self.top_k_scores) > self.k: + heapq.heappop(self.top_k_scores) + return self.top_k_scores[0] +``` + +## Min Heapの実装 +heap の実装って内部的にどうやってるのかなーと思ったけど内部的にはcで配列のポインタの位置でheapを動かしてた。 +https://github.com/python/cpython/blob/3.14/Lib/heapq.py + +heapの実装は別ファイル。