-
Notifications
You must be signed in to change notification settings - Fork 0
703. Kth Largest Element in a Stream #9
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: main
Are you sure you want to change the base?
Conversation
def __init__(self, k: int, nums: List[int]): | ||
self.k = k | ||
self.sorted_nums = [] | ||
nums.sort(reverse=True) |
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.
関数を呼び出す側としては、ある関数を呼び出したときに、渡した引数の中身が変更されることは、あまり想定しないように思います。関数内では原則引数の中身を変更しないことをお勧めいたします。また、特別な理由があって変更する場合は、関数コメント等に明示的にその旨を書くことをお勧めいたします。
self.sorted_nums = [] | ||
nums.sort(reverse=True) | ||
|
||
i = 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.
self.sorted_nums = nums[-k:]
でよいと思います。
if len(self.sorted_nums) < self.k: | ||
self.sorted_nums.append(val) | ||
self.sorted_nums.sort(reverse=True) | ||
elif self.sorted_nums[self.k-1] > val: |
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://peps.python.org/pep-0008/#other-recommendations
Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
https://google.github.io/styleguide/pyguide.html#36-whitespace
Use your better judgment for the insertion of spaces around arithmetic operators (+, -, *, /, //, %, **, @).
## nums.sort(), sorted(nums), nums = SortedList()の違いとheapとの比較 | ||
- sort()とsorted()の違いは、前者が元のリストを変えるのに対して後者は新しいリストを作成して元のリストには影響がない点. | ||
- SortedList()は追加したときに自動的にsortされる点 | ||
- sort()とsorted()はTimSortを使用しておりO(nlogn)、SortedList()はO(nlogn)で動く(なんのソートかは探し出せなかった) |
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.
SortedList はたしか非標準でしたね。
https://docs.python.org/3/library/heapq.html#heapq.heappushpop
あと、heapq のドキュメントを見ておきましょう。(これからも、なにか標準関数を呼ぶ時、ドキュメントを読んだ記憶がなければ開いて読んでみてください。)
heappushpop, heapreplace などがあります。
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.
豆知識ですが、3.11からpowersortが使われているみたいですね。
https://www.i-programmer.info/news/216-python/15954-python-now-uses-powersort.html
No description provided.