Skip to content

347 top k frequent elements#9

Open
kitano-kazuki wants to merge 11 commits intomainfrom
347-top-k-frequent-elements
Open

347 top k frequent elements#9
kitano-kazuki wants to merge 11 commits intomainfrom
347-top-k-frequent-elements

Conversation

@kitano-kazuki
Copy link
Copy Markdown
Owner

def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if k <= 0:
raise ValueError("k must be more than 0.")
value_to_count = {}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

collections.defaultdict を使うと、もう少しシンプルに書けると思います。
https://docs.python.org/ja/3.14/library/collections.html#collections.defaultdict

value_to_count = {}
for num in nums:
value_to_count[num] = value_to_count.get(num, 0) + 1
max_heap = []
Copy link
Copy Markdown

@TrsmYsk TrsmYsk Mar 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

heapqモジュールはmax heap用の関数群も用意してくれているので、それらを使っていないのにmax_heapという名づけをすると読み手が混乱するような気がします。
https://docs.python.org/3.14/library/heapq.html
振り返りコメントにもありましたが、要素数をkに抑えて、top_kみたいに名付けるのが一番素直かなと思います。

pivot = num_to_counts[unique_nums[right]]
partition_idx = left
for i in range(left, right):
if num_to_counts[unique_nums[i]] <= pivot:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

条件分岐をif num_to_counts[unique_nums[i]] > pivot:にしてcotinueすることで、ll.276-277のインデントを上げてもいいのかなと思いました。たぶん趣味の範囲です。

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