Conversation
t9a-dev
reviewed
Dec 5, 2025
| return top_k_frequenct_elements | ||
| ``` | ||
| https://github.com/potrue/leetcode/pull/9#discussion_r2083523591 | ||
| 以上を参考に, bucketの初期化部分を以下のように変更したところ3ms程度まで短縮できた. |
There was a problem hiding this comment.
今回のケースには当てはまらないかも知れませんが、可読性を犠牲に速度を求めるのかという視点もあります。
t0hsumi/leetcode#1 (comment)
olsen-blue/Arai60#34 (comment)
nodchip
reviewed
Dec 5, 2025
|
|
||
| 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)] |
There was a problem hiding this comment.
return numbers_sorted_by_count[:k]のほうがシンプルだと思いました。
Owner
Author
There was a problem hiding this comment.
ありがとうございます
何故か複雑な書き方をしてました…
| ```py | ||
| class Solution: | ||
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
| number_to_count = {} |
There was a problem hiding this comment.
defaultdict を用いることで、シンプルにすることができると思います。
number_to_count = defaultdict(int)
for num in nums:
number_to_count[num] += 1
TakayaShirai
reviewed
Dec 8, 2025
Comment on lines
+51
to
+52
| for number, frequency in number_to_frequency.items(): | ||
| heapq.heappush(heap, (-frequency, number)) |
There was a problem hiding this comment.
状況にもよると思いますが、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))
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
解く問題
Top K Frequent Elements
次に解く問題
Find K Pairs With Smallest Sums