Conversation
| heapq.heapify(self.top_k_values) | ||
| self._reduce_heapq_length_below_k() | ||
|
|
||
| def _reduce_heapq_length_below_k(self): |
There was a problem hiding this comment.
レビューと言うより感想に近いのですが、メソッド名が少し長いなと感じました。_keep_top_k_valuesなどが良いかなと思ったのですが、あまり長さは変わらないですね。
別の考え方としてaddメソッドに集約して初期化時にaddを利用するといった方法を見かけた気がします。
def __init__(self, k: int, nums: List[int]):
self.k = k
self.top_k_values = []
for n in nums:
self.add(n)
def add(self, val: int) -> int:
heapq.heappush(self.top_k_values, val)
if len(self.top_k_values) > self.k:
heapq.heappop(self.top_k_values)
return self.top_k_values[0]There was a problem hiding this comment.
今回の問題の要件ですと下記の通りストリーム処理となっておりますので、t9a-devさんの方針がしっくりきました。
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of test scores nums.
| def add(self, val: int) -> int: | ||
| # 2分探索で位置を更新. | ||
| index_to_insert = self.bin_search(val) | ||
| self.nums = self.nums[:index_to_insert] + [val] + self.nums[index_to_insert: ] |
There was a problem hiding this comment.
明言はしてなさそうですがスライスのコロンの両サイドは同じスペースとなるので[index_to_insert:]がいいのではないでしょうか。
However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted, the space is omitted:
https://peps.python.org/pep-0008/#pet-peeves
| ``` | ||
| ```py | ||
| def _siftdown(heap, startpos, pos): | ||
| newitem = heap[pos] |
There was a problem hiding this comment.
細かいですがこの解法だけ変数名の付け方が他のと異なるのが気になりました。
newitem => new_item
parentpos => parent_pos
endpos => end_pos
となるのかなと思いました。
There was a problem hiding this comment.
横からですが、こちら変数名の付け方が異なるのは、Yuto729 さんが書いたものではなく、cpython のソースコードが記載されているためだと思います!
|
個人的には特に気になる部分はなく、読みやすかったと思います。ヒープに関しては、一度自分で実装してみると理解が深まるため、時間があるときに実装してみると良いと思います!個人的には以下の動画が参考になりました(結構長いです)。 |
解く問題
Kth Largest Element In A Stream
次に解く問題
Top K Frequent Elements