Skip to content

347. Top K Frequent Elements#9

Open
rimokem wants to merge 1 commit into
mainfrom
0347-top-k-frequent-elements
Open

347. Top K Frequent Elements#9
rimokem wants to merge 1 commit into
mainfrom
0347-top-k-frequent-elements

Conversation

@rimokem
Copy link
Copy Markdown
Owner

@rimokem rimokem commented Mar 30, 2026

Comment thread 0347/memo.md

top_k_sorted = []
while top_k:
top_k.append(heapq.heappop(top_k))
Copy link
Copy Markdown

@Manato110 Manato110 Mar 30, 2026

Choose a reason for hiding this comment

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

細かい指摘になってしまうのですが、
memo.mdの方で、top_kに追加していて無限ループになっていますね
恐らくtop_k.appendtop_k_sorted.append

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ご指摘ありがとうございます。

間違ったコードをコピペしてしまいました。
step3.pyの方が正しいコードです。

Comment thread 0347/step3.py
if len(top_k) > k:
heapq.heappop(top_k)

top_k_sorted = []
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ascendingなどとつけてもわかりやすいかもです。

Comment thread 0347/memo.md
if len(top_k) > k:
heapq.heappop(top_k)

return [n for _, n in top_k]
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

このコードで使用しているnnumのほうがいいかなと思いました。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

レビューありがとうございます。
他の方のコードをいくつか見たところ、確かにほとんどの方がnumで書いていますね。
そこまで気が回っていませんでした。

興味本位の質問なのですが、ここでnumを使うの理由としては、以下の2通りが思いつきました。

  1. numsがあるから、その単数形としてnum
  2. 一文字変数は気持ちが悪いからnは避ける

どちらの理由が近いですか。(何か他の理由もあったら教えていただけると嬉しいです)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

私はどちらでもいいが、微かに num のほうがいいかも、くらいの感覚です。
一文字変数を使うときは、だいたい2,3行で忘れていい変数に使うんですね。

これ、n がほぼ同じ意味の nums の要素が流れ着いたものという意味で、3つのループ(内包表記含む)で使われていますね。もうちょっと意識していて欲しい範囲が長いです。

まあ、でもあんまりまじめに主張するほどの話ではないです。

Comment thread 0347/memo.md
```python
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
num_to_count = {}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この用途であれば、 collections.Counter が便利かもしれません。
https://docs.python.org/3/library/collections.html#collections.Counter

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.

6 participants