Update 347.Top K Frequent Elements.md - #9
Conversation
| ```python | ||
| class Solution: | ||
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
| element_counter = {} |
There was a problem hiding this comment.
この用途であれば、 defaultdict や Counter のほうがシンプルに書けると思います。
https://docs.python.org/ja/3.14/library/collections.html#collections.defaultdict
https://docs.python.org/ja/3.14/library/collections.html#collections.Counter
There was a problem hiding this comment.
defaultdict知りませんでした、ありがとうございます。
存在しないキーを読んだときにデフォルト値を生成してくれるんですね。
element_counter[num] = element_counter + 1
でokになる。
| heapq.heappop(heap) | ||
|
|
||
| res = [] | ||
| print(heap) |
There was a problem hiding this comment.
デバッグ出力は削除してからレビューに回したほうが良いと思います。そのほうが、レビューワーにとってノイズとならないと思います。
| ```python | ||
| class Solution: | ||
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
| element_counter = {} |
There was a problem hiding this comment.
dict 型の変数名はキーと値にどのような値が含まれるかを表すようにすると、読み手にとって理解しやすくなると思います。今回の場合は num_to_frequency あたりになると思います。ただ、 element_counter でも acceptable だと思います。
| for num in nums: | ||
| element_counter[num] = 1 + element_counter.get(num, 0) | ||
|
|
||
| heap = [] |
There was a problem hiding this comment.
こちらのコメントをご参照ください。
rimokem/arai60#25 (comment)
今回の場合は frequencies_and_nums はいかがでしょうか?
There was a problem hiding this comment.
ありがとうございます
個人的にはどのような値が格納されているかに着目したいです
このあたりを意識してみます
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
| element_counter = {} | ||
| for num in nums: | ||
| element_counter[num] = 1 + element_counter.get(num, 0) |
There was a problem hiding this comment.
自分なら element_counter.get(num, 0) + 1 と書くと思います。理由は b + a * x より a * x + b と書くほうが自然に感じるためです。趣味の範囲だと思います。
今回解いた:https://leetcode.com/problems/top-k-frequent-elements/
次回:https://leetcode.com/problems/find-k-pairs-with-smallest-sums/