49. Group Anagrams#12
Conversation
seal-azarashi
left a comment
There was a problem hiding this comment.
各解法やそれぞれに至る過程での調査等、全体通してとてもよく出来ていると思いました。
強いて付け加えるなら、Leetcode では constraints として明記されているので問題ではないのですが、実際のプロダクトに対してこれを実装することを想定すると、引数 strs の要素には lowercase English letters しかないことが明記されていたり、そういった仕様が docstring にしっかり書かれているとより適切な実装になるのかなと思います。
| https://github.com/rihib/leetcode/pull/8#:~:text=Python%E3%81%AB%E3%81%8A%E3%81%91%E3%82%8B%7B%7D,leetcode%2313%20(comment) | ||
|
|
||
| https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/use-list-literal.html | ||
| 時間計算量:O(n ^ mlogm) strs の長さを n, string の長さを m とする |
There was a problem hiding this comment.
O(n * mlogm) ではないでしょうか?
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = defaultdict(list)
for string in strs: # n回のループ
sorted_string_list = sorted(string) # O(mlogm)
sorted_string = "".join(sorted_string_list) # O(m)
anagrams[sorted_string].append(string) # O(1)
return list(anagrams.values()) # O(n)
There was a problem hiding this comment.
確かに累乗ではなく、O(n * mlogm) が正しいですね。
ご指摘ありがとうございます。
|
他にも入力が英小文字のみで構成されるという前提の元、charのヒストグラムを作りそれをkeyとしたhashmapのvalueに文字列を格納していくという方法もあります |
これは思いつかなかったので、こちらも書いてみます。 |
バケットソートの要領ですね。 |
| ちなみに dict の.values()はリストではなく、view_object を返す | ||
| https://docs.python.org/3/library/stdtypes.html#dict-views | ||
|
|
||
| 普通の dict を使うと、キーの存在チェックと初期化が必要になるため、defaultdict を使用している。 |
|
拝見しました。
こういう心構えを自分も大事にしたいと思いました |
| ```python | ||
| class Solution: | ||
| def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
| anagram_pairs = defaultdict(list) |
There was a problem hiding this comment.
pairだと1対の2つの要素という印象を受けてしまうので、groupの方が良いのではないかと思いました
| どちらも計算量的には O(n)だが、.join()はメモリの再割り当てが 1 回で済むように最適化されている?ので、 | ||
| .join()のほうが定数倍早いのではないかと思う。(CPython の実装を見た) |
There was a problem hiding this comment.
tupleもjoinもメモリ割り当ては一回で済んでる様に見えたんですが、これのソース教えていただけますか?
- join
- tuple
https://leetcode.com/problems/group-anagrams/description/