diff --git a/349. Intersection of Two Arrays.md b/349. Intersection of Two Arrays.md new file mode 100644 index 0000000..8a2d5b9 --- /dev/null +++ b/349. Intersection of Two Arrays.md @@ -0,0 +1,62 @@ +1st +それぞれの配列の要素を set に格納し、両方の set に含まれているものを結果用の set に格納すればいけそう。 +時間計算量:O(n + m) num1 の長さを n、nums2 の長さを m とする +空間計算量:O(n + m) + +```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + unique_nums1 = set() + unique_nums2 = set() + intersection_result = set() + + for num in nums1: + unique_nums1.add(num) + + for num in nums2: + unique_nums2.add(num) + + for num in unique_nums1: + if num in unique_nums2: + intersection_result.add(num) + + return list(intersection_result) + +``` + +2nd +set について調べていると、 +`intersection()`というメソッドがあったのでこれも使える。 + +https://docs.python.org/ja/3/library/stdtypes.html#frozenset.intersection + +```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + num1_set = set(nums1) + num2_set = set(nums2) + return list(num1_set.intersection(num2_set)) +``` + +&でも積集合を求めることができるらしい。 +気になったので、ここの実装を調べてみた。 +& 演算子は、Python の set クラスでオーバーロードされており、**and** メソッドを呼び出していた。 + +https://github.com/python/cpython/blob/bd4be5e67de5f31e9336ba0fdcd545e88d70b954/Lib/_collections_abc.py#L60 + +```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + return list(set(nums1) & set(nums2)) +``` + +3rd +&演算子が一番完結、かつ、bit 演算の&と同じで積を取っていることがわかりやすいので、こちらを採用 + +```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + nums1_set = set(nums1) + nums2_set = set(nums2) + return list(nums1_set & nums2_set) +```