347. Top K Frequent Elements#10
Conversation
| - カウント部分が O(n) | ||
| - ヒープ化が O(n) | ||
| - 取り出すところが pop O(log n) をk 回で O(k log n) | ||
|
|
||
| なので O(k * log n) |
There was a problem hiding this comment.
時間計算量は O(n + k log n) のほうがより丁寧だと思いました.
n = k, n <= k などの場合でそれぞれ異なるように思います.
There was a problem hiding this comment.
ありがとうございます。特にkが小さい場合などはnの方が大きく効いてくるので、そちらが正しそうですね。
| class Solution: | ||
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
| # counter の value は [回数, 値]のリスト | ||
| counter: Dict[int, List[int]] = {} |
There was a problem hiding this comment.
妙案が思い浮かばないんですが, counter という名前を少し変更したい気持ちになっています.
counterという名称から推測するよりも構造が複雑だったので.
There was a problem hiding this comment.
確かにそうですね
他の方にいただいたコメントのように、構造の方を単純にしてしまうというのが今回はいいのかもしれません:
#10 (comment)
There was a problem hiding this comment.
num_to_count_and_num という名前は思いついたのですが、野暮ったく感じました。構造のほうを単純にしてしまったほうが良いと思います。
There was a problem hiding this comment.
ありがとうございます。構造が複雑だとどうしても名前も複雑になりそうで、名前を工夫するより大元を解決するようが良さそうですね。
There was a problem hiding this comment.
この方のPRも,いろんな解法のパターンが記載されていて,個人的には勉強になりましたので貼っておきます
https://github.com/dorxyxki/arai60/pull/9/changes
| else: | ||
| counter[num][0] += 1 | ||
|
|
||
| count_and_num = list(counter.values()) |
There was a problem hiding this comment.
counterは値: 出現回数で持っておいて、count_and_numを作るときに
count_and_num = [(count, num) for num, count in counter.items()]と組にするのはどうでしょうか。
keyとvalueでnumが重複している冗長さが消えるので、個人的にはこちらが良いと感じます。
There was a problem hiding this comment.
ありがとうございます。私も必要以上に複雑な構造になっていそうだったのが気になっていましたがそのように書くのがシンプルで良さそうです。
この問題:https://leetcode.com/problems/top-k-frequent-elements/
次の問題:https://leetcode.com/problems/find-k-pairs-with-smallest-sums/