Conversation
| ```python | ||
| class Solution: | ||
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
| def quick_select(left, right): |
There was a problem hiding this comment.
好みの問題だと思いますが、僕ならquick_select()の引数をlist, left, right, pivot_indexの4つになる様に書くかなと思いました。
There was a problem hiding this comment.
今回は以前に書いていた方のを写しただけでして、そこまでは思い至りませんでした。
自分で0から書くときはその方法も検討させていただきます。
| count[num] = 1 | ||
|
|
||
| count_sorted = sorted(count.items(), reverse=True, key=lambda x:x[1]) | ||
| k_elements = [count_sorted[i][0] for i in range(k)] |
There was a problem hiding this comment.
確かにその通りです。
書いた当時は少し複雑に考えすぎていました。
| - 負のカウントも取れる | ||
| - 独自メソッド | ||
| - elements | ||
| - most_common |
There was a problem hiding this comment.
GitHub に CPython のソースがあるので、実装を読んでみてもいいでしょう。読み始めるのはもう少し先でもいいです。
There was a problem hiding this comment.
ありがとうございます。
自分にはまだ難易度が高いですがチャレンジすることも意識してみようと思います。
| num_to_count = {} | ||
| for num in nums: | ||
| if num not in num_to_count: | ||
| num_to_count[num] = 0 | ||
| num_to_count[num] += 1 |
There was a problem hiding this comment.
未処理のキーに対応するデフォルト値は defaultdict を使うと指定できます。
num_to_count = defaultdict(int)
for num in nums:
num_to_count[num] += 1There was a problem hiding this comment.
ご指摘ありがとうございます。defaultdictは検討しましたが、中身をきちんと理解していないので今回は使わないこととしました。
| partition_index += 1 | ||
| values[right], values[partition_index] = values[partition_index], values[right] | ||
| if partition_index == k - 1: | ||
| return |
There was a problem hiding this comment.
同じ関数の中で値を返さない return と返す return が混在しているのが気になりました。この関数は出力として値を返さないため、値を返さないほうに統一するとよいと思います。
if partition_index == k - 1:
return
elif partition_index < k - 1:
quick_select(partition_index + 1, right)
elif partition_index > k - 1:
quick_select(left, partition_index)
There was a problem hiding this comment.
ありがとうございます。
出力を返すかどうかはあまり考えていなかったので参考になります。
| - (key:value)をどうやってheap queにすればいいのかわからない。 | ||
| - (value, key)のtupleにしてheap queに追加する |
| if len(result) >= k: | ||
| return result[:k] |
There was a problem hiding this comment.
num の種類が k 未満の場合には、return に到達せずに for ループを終えるので None を返してしまいそうです。
k 未満の場合の対応をどうするかにもよりますが、他の実装(L104 return [value for _, value in frequent_values] や L212 return [num for _, num in top_k_heap])ではある分だけ返すようになっていたので、それに合わせるとこんな感じがよいかもです。またその場合にはスライスせず result で十分そうです。
| if len(result) >= k: | |
| return result[:k] | |
| if len(result) >= k: | |
| break | |
| return result |
問題文
https://leetcode.com/problems/top-k-frequent-elements/description/