-
Notifications
You must be signed in to change notification settings - Fork 0
Kth largest element in a stream #38
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
base: arai60
Are you sure you want to change the base?
Conversation
|
Priority Queue を自前で実装することを oda さんが推奨されてました。 |
| def add(self, val: int) -> int: | ||
| # Add new value and pop until len(self._min_heap) == self.k | ||
| heapq.heappush(self._min_heap, val) | ||
| while len(self._min_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.
ifでもよさそうかな?とおもいました!
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.
1個ずつしかでないので確かにそれでいいですね
|
レビュー完了しました! |
| def add(self, val: int) -> int: | ||
| if len(self._min_heap) < self.k: | ||
| heappush(self._min_heap, val) | ||
| elif val >= self._min_heap[0]: |
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://github.com/python/cpython/blob/b765e4adf858ff8a8646f38933a5a355b6d72760/Lib/heapq.py#L163
heappushpop このチェックしてそうですよ。
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 len(self._min_heap) < self.k: | ||
| heappush(self._min_heap, val) | ||
| elif val >= self._min_heap[0]: |
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, elif で関心の対象は揃えた方が読みやすいと思います
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とelifの使い分けが自分の中でイマイチできていませんでしたがこの説明が腑に落ちました。
問題
703. Kth Largest Element in a Stream