Skip to content
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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Add 703. Kth Largest Element in a Stream.md #8

wants to merge 2 commits into from

Conversation

t0hsumi
Copy link
Owner

@t0hsumi t0hsumi commented Dec 10, 2024

思ったこと
- 変数名について、heapを用いる解法では`kth_largest`とかそういう名前が多かった。確かに、`heapq.heappush`とかやっているので`heap`だけでは不十分だと感じた。
- `__init__()`にて`add()`を呼ぶ解法も多かった。コードの重複がないので、その解法の方が、コンパクトに収まる様に感じた。

Copy link

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 を使うたびに見る、みたいなのはやりすぎだとは思いますが、時々目を通すといいでしょう。

参考: https://note.com/nir29/n/n025ddc315a2e

Copy link

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}')
Copy link

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:

Copy link

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:
Copy link

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 されないように見えます。

Copy link
Owner Author

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:
Copy link

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):
のほうが分かりやすいと思います。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants