Skip to content

347: Top K Frequent Elements#15

Open
Yuto729 wants to merge 1 commit intomainfrom
top-k-frequent-elements
Open

347: Top K Frequent Elements#15
Yuto729 wants to merge 1 commit intomainfrom
top-k-frequent-elements

Conversation

@Yuto729
Copy link
Owner

@Yuto729 Yuto729 commented Dec 5, 2025

@Yuto729 Yuto729 changed the title Top K Frequent Elements 347: Top K Frequent Elements Dec 5, 2025
Repository owner deleted a comment from github-actions bot Dec 5, 2025
return top_k_frequenct_elements
```
https://github.com/potrue/leetcode/pull/9#discussion_r2083523591
以上を参考に, bucketの初期化部分を以下のように変更したところ3ms程度まで短縮できた.
Copy link

Choose a reason for hiding this comment

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

今回のケースには当てはまらないかも知れませんが、可読性を犠牲に速度を求めるのかという視点もあります。
t0hsumi/leetcode#1 (comment)
olsen-blue/Arai60#34 (comment)


sorted_number_to_count = dict(sorted(number_to_count.items(), reverse=True, key=lambda item: item[1]))
numbers_sorted_by_count = list(sorted_number_to_count.keys())
return [numbers_sorted_by_count[i] for i in range(k)]
Copy link

Choose a reason for hiding this comment

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

return numbers_sorted_by_count[:k]

のほうがシンプルだと思いました。

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます
何故か複雑な書き方をしてました…

```py
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
number_to_count = {}
Copy link

Choose a reason for hiding this comment

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

defaultdict を用いることで、シンプルにすることができると思います。

number_to_count = defaultdict(int)
for num in nums:
    number_to_count[num] += 1

Comment on lines +51 to +52
for number, frequency in number_to_frequency.items():
heapq.heappush(heap, (-frequency, number))

Choose a reason for hiding this comment

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

状況にもよると思いますが、nums の要素数に比べて k がかなり小さい場合などは、以下のように k 個の要素のみをヒープに残す方が、 push や pop の操作で内部でヒープを更新するのに必要な処理を減らせて良さそうです。

for number, frequency in number_to_frequency.items():
    if len(heap) < k:
        heapq.heappush(heap, (frequency, number))
            continue
    
    if frequency > heap[0][0]:
        heapq.heappushpop(heap, (frequency, number))

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