Skip to content

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

rinost081
Copy link
Owner

No description provided.

def __init__(self, k: int, nums: List[int]):
self.k = k
self.sorted_nums = []
nums.sort(reverse=True)
Copy link

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

@nodchip nodchip Dec 8, 2024

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

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)で動く(なんのソートかは探し出せなかった)
Copy link

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 などがあります。

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

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.

4 participants