-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add 703. Kth Largest Element in a Stream.md #8
base: main
Are you sure you want to change the base?
Conversation
思ったこと | ||
- 変数名について、heapを用いる解法では`kth_largest`とかそういう名前が多かった。確かに、`heapq.heappush`とかやっているので`heap`だけでは不十分だと感じた。 | ||
- `__init__()`にて`add()`を呼ぶ解法も多かった。コードの重複がないので、その解法の方が、コンパクトに収まる様に感じた。 | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://docs.python.org/3/library/heapq.html#heapq.heappushpop
heapq の標準ドキュメントを見たことがなければざっと目を通しておいてください。たとえば、heappushpop などがあったりします。dict を使うたびに見る、みたいなのはやりすぎだとは思いますが、時々目を通すといいでしょう。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(おっと、heappushpop 使っていましたね。)
|
||
def __init__(self, k: int, nums: List[int]): | ||
if k <= 0 or k > len(nums) + 1: | ||
raise ValueError(f'Invalid input value k = {k}') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://docs.python.org/3/library/exceptions.html#ValueError
そうですね。これは ValueError が適切と思います。
|
||
|
||
class KthLargest: | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
class の次の行は空けないことが多い気がしますが趣味の範囲でしょう。
self.heap: List[int] = [] | ||
self.k = k | ||
for num in nums: | ||
if len(self.heap) < self.k: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
len(self.heap) == self.k のときに push されないように見えます。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
コメントありがとうございます。
とりあえずpushをして、kを超える要素数があればpopする方がみよいですね。
class KthLargest: | ||
|
||
def __init__(self, k: int, nums: List[int]): | ||
if k <= 0 or k > len(nums) + 1: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if not 0 < k <= len(nums):
のほうが分かりやすいと思います。
https://leetcode.com/problems/kth-largest-element-in-a-stream/description/