347. Top K Frequent Elements#9
Conversation
|
|
||
| top_k_sorted = [] | ||
| while top_k: | ||
| top_k.append(heapq.heappop(top_k)) |
There was a problem hiding this comment.
細かい指摘になってしまうのですが、
memo.mdの方で、top_kに追加していて無限ループになっていますね
恐らくtop_k.append ⇒ top_k_sorted.append
There was a problem hiding this comment.
ご指摘ありがとうございます。
間違ったコードをコピペしてしまいました。
step3.pyの方が正しいコードです。
| if len(top_k) > k: | ||
| heapq.heappop(top_k) | ||
|
|
||
| top_k_sorted = [] |
| if len(top_k) > k: | ||
| heapq.heappop(top_k) | ||
|
|
||
| return [n for _, n in top_k] |
There was a problem hiding this comment.
レビューありがとうございます。
他の方のコードをいくつか見たところ、確かにほとんどの方がnumで書いていますね。
そこまで気が回っていませんでした。
興味本位の質問なのですが、ここでnumを使うの理由としては、以下の2通りが思いつきました。
numsがあるから、その単数形としてnum- 一文字変数は気持ちが悪いから
nは避ける
どちらの理由が近いですか。(何か他の理由もあったら教えていただけると嬉しいです)
There was a problem hiding this comment.
私はどちらでもいいが、微かに num のほうがいいかも、くらいの感覚です。
一文字変数を使うときは、だいたい2,3行で忘れていい変数に使うんですね。
これ、n がほぼ同じ意味の nums の要素が流れ着いたものという意味で、3つのループ(内包表記含む)で使われていますね。もうちょっと意識していて欲しい範囲が長いです。
まあ、でもあんまりまじめに主張するほどの話ではないです。
| ```python | ||
| class Solution: | ||
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
| num_to_count = {} |
There was a problem hiding this comment.
この用途であれば、 collections.Counter が便利かもしれません。
https://docs.python.org/3/library/collections.html#collections.Counter
今回の問題
https://leetcode.com/problems/top-k-frequent-elements/
次回の問題
https://leetcode.com/problems/find-k-pairs-with-smallest-sums/