Skip to content

349. Intersection of Two Arrays.md #12

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 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions 349. Intersection of Two Arrays.md
Original file line number Diff line number Diff line change
@@ -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
Copy link

Choose a reason for hiding this comment

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

これは、まあ、これでいいんですが、もう少し書き方にバリエーションがあるように思います。挙げてみますか?

たとえば、追加質問で考えられるのは、「片方がとても大きくて、片方がとても小さいときには、大きい方を set にするのは大変じゃないでしょうか、特に大きいほうが sort 済みのときにはどうしますか。」とかです。

Copy link

Choose a reason for hiding this comment

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

レビュー者ですが、この視点はなかったです。たしかにこのコードだとlen(nums1)が1e8とかでlen(nums2)が空リストだと無駄な計算をすることになりますね

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます!
他の解き方を選択するときの気持ち?状況?みたいなものがイメージできてなかったので、状況を例示いただけたことでイメージができてとっつきやすいです。

この状況についても考えてみました。「ソートされてるということを活用して、長い方は全部みたくないから二分探索を活用したいな」みたいなことを考えながら以下のように解いてみます。

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # nums1: とても大きくてsort済み
        # nums2: とても小さい

        # sort済みという状況を再現するために、nums1をsortする
        nums1.sort()

        intersections = []
        for num in nums2:
            if num in intersections:
                continue
            left = -1
            right = len(nums1)
            while right - left > 1:
                middle = (left + right) // 2 
                if nums1[middle] == num:
                    intersections.append(num)
                    break
                if nums1[middle] < num:
                    left = middle
                else:
                    right = middle
        return intersections

Copy link

Choose a reason for hiding this comment

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

そうですね。

他、両方ソートされていてとても大きければ、マージソートの変形のように書くと思います。

要するにこの問題の推定される出題意図は条件を変えたときに案がいくつか出てくるかです。


- 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))
```