diff --git a/349. Intersection of Two Arrays.md b/349. Intersection of Two Arrays.md new file mode 100644 index 0000000..38c144e --- /dev/null +++ b/349. Intersection of Two Arrays.md @@ -0,0 +1,75 @@ +URL: https://leetcode.com/problems/intersection-of-two-arrays/description/ + +# Step 1 + +- 実装時間: 3分 +- nums1の長さをn, nums2の長さをmとして、 + - 時間計算量: O(n + m) + - 空間計算量: O(n + m) + +```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + return list(set(nums1) & set(nums2)) +``` + +# Step 2 + +- 気になったので、setのintersectionの実装を確認した。 + - 「otherを順番に見ていって、自分に含まれていればresultに追加」というシンプルなアルゴリズムみたい。 + - https://github.com/python/cpython/blob/39e69a7cd54d44c9061db89bb15c460d30fba7a6/Objects/setobject.c#L1354-L1355 + +- 参考にしたURL + - https://github.com/nittoco/leetcode/pull/15 + - https://github.com/fhiyo/leetcode/pull/16 + - https://github.com/TORUS0818/leetcode/pull/15 + - https://github.com/hayashi-ay/leetcode/pull/21 + - https://github.com/Ryotaro25/leetcode_first60/pull/14 + - https://github.com/Mike0121/LeetCode/pull/30 + - https://github.com/kazukiii/leetcode/pull/14 + - https://github.com/Yoshiki-Iwasa/Arai60/pull/12 + - https://github.com/SuperHotDogCat/coding-interview/pull/33 + - https://github.com/seal-azarashi/leetcode/pull/13 + - https://github.com/hroc135/leetcode/pull/13 + - https://github.com/tarinaihitori/leetcode/pull/13 + - https://github.com/colorbox/leetcode/pull/27 + +- setのdocsも再度みといた + - https://docs.python.org/ja/3/library/stdtypes.html#set-types-set-frozenset + - frozensetがあるというのはわかったけど、どういう状況で役に立つのだろう。。。 + - > 一方、frozenset 型はイミュータブルで、ハッシュ可能 です。作成後に内容を改変できないため、辞書のキーや他の集合の要素として用いることができます。 + +- https://wiki.python.org/moin/TimeComplexity#set + - このドキュメントの存在を知らなかった。 + +- > (nanの挙動について)IEEE754を確認しておいてください。 + - https://pystyle.info/floating-point-numbers/ + - https://zehnpaard.hatenablog.com/entry/2022/05/30/084212 + + +- `&`が機能するのはなぜか + - `&`は`__and__`を呼んでいて、iterable同士の要素の共通部分を返している。 + - https://github.com/SuperHotDogCat/coding-interview/pull/33/files#r1654937009 + +- 「setに変換したりlistに変換したりするのって意外と抵抗がある」 + - この感覚は持ってなかった。 + - 変換にはすべての要素を走査するコストがあるので、その点を理解する必要がある。 + - https://github.com/nittoco/leetcode/pull/15#discussion_r1632066961 + +```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + return list(set(nums1) & set(nums2)) +``` + +# Step 3 + +- nums1の長さをn, nums2の長さをmとして、 + - 時間計算量: O(n + m) + - 空間計算量: O(n + m) + +```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + return list(set(nums1) & set(nums2)) +```