Skip to content

Add 347. Top K Frequent Elements.md #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Add 347. Top K Frequent Elements.md #9

wants to merge 2 commits into from

Conversation

t0hsumi
Copy link
Owner

@t0hsumi t0hsumi commented Dec 11, 2024

```python
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
occurrences: dict[Tuple(int, int)] = {}

Choose a reason for hiding this comment

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

Type Hintが違うような気がします。 dict[int, int]かなと。
https://docs.python.org/3/library/typing.html#generics

Copy link
Owner Author

Choose a reason for hiding this comment

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

ご指摘ありがとうございます。間違ってますね。

自分の方でも確認しました。https://docs.python.org/3/library/stdtypes.html#types-genericalias:~:text=Another%20example%20for,their%20second%20argument%3A

frequencyを数える->frequencyを降順にソートする->値の大きいものから取り出してリストを作成が基本的な流れだと思った。

frequencyを数える作業をどうするか迷った。とりあえず思いついたのは、与えられた`nums`をソートして
それに対してループで走査してfrequencyを数える方法。`nums`が与えられているので、`sorted_numbers`ではなく`sorted_nums`と略しても許容範囲かと判断した。与えられた`nums`からfrequencyを数える時にも、frequencyの大きいものを順に取り出す時にもheapは使えるが、計算量が変わらない上にpythonのデフォルトはmin-heapなので`(-1 * number_of_appears, number)`にする必要があり、複雑に感じたので使わなかった。

Choose a reason for hiding this comment

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

計算量が変わらない上にpythonのデフォルトはmin-heapなので(-1 * number_of_appears, number)にする必要があり、複雑に感じたので使わなかった。

min-heap を max-heap として無理やり使うのが複雑であるというのは僕も同意です。(今回は使用しないという判断なので関係ないですが)仮に使う場合はコメントを残すことは必須かなと個人的には思っています。

Comment on lines +80 to +83
if num not in occurrences:
occurrences[num] = 1
else:
occurrences[num] += 1

Choose a reason for hiding this comment

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

以下書き方のほうが個人的には好きです。

Suggested change
if num not in occurrences:
occurrences[num] = 1
else:
occurrences[num] += 1
if num not in occurrences:
occurrences[num] = 0
occurrences[num] += 1

while index < len(sorted_nums) and sorted_nums[index] == number:
index += 1
number_of_appears += 1
frequency.append((number_of_appears, number))

Choose a reason for hiding this comment

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

個人的な好みのお話で、ここの while - while について他の書き方もしてみたくなりました。
下記、ループの外側で最後の追加をしていて微妙ですが、こんな感じにも書けそうです。

        if len(sorted_nums) == 0:
            return []
        number: int = sorted_nums[0]
        number_of_appears: int = 1
        for i in range(1, len(sorted_nums)):
            if sorted_nums[i] == number:
                number_of_appears += 1
                continue
            frequency.append((number_of_appears, number))
            number = sorted_nums[i]
            number_of_appears = 0
        frequency.append((number_of_appears, number))

Copy link
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます。

こちらの方はネストが少ない分の読みやすさがありますね。

occurrences[num] += 1
```
- dictを用いない場合では、Counterを使い、`most_common`を呼び出す。
https://docs.python.org/3/library/collections.html#collections.Counter
Copy link

Choose a reason for hiding this comment

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

いいですね。
せっかくなので実装も見ておきましょう。何を使っていて自分のと比べてどう思いますか。
https://github.com/python/cpython/blob/main/Lib/collections/__init__.py

Copy link
Owner Author

Choose a reason for hiding this comment

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

共通点

相違点

思ったこと
今回は数字の出現頻度を数える問題だったので、それに特化したCounterの方が余計にheapを用意する必要もなく、見やすい様に感じました。
ただ、もともと用意されているCounterのmethodを用いた実装と、defaultdictで足りない出現頻度の高い値を求める部分を自分でheapを使って調べた実装とでやっていることがそう大きくは変わらない印象も受けました。

num_to_count[num] += 1

if not 0 < k <= len(num_to_count):
raise ValueError(
Copy link

Choose a reason for hiding this comment

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

https://docs.python.org/3/library/exceptions.html#ValueError
時々、どのような Exception が定義されているか眺めてみましょう。

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.

5 participants