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

Conversation

katataku
Copy link
Owner

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.

そうですね。

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

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

Copy link

@hayashi-ay hayashi-ay left a comment

Choose a reason for hiding this comment

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

良いと思います。setintersectionメソッドや他の集合演算のメソッドにも目を通しておくと良いと思います。

https://docs.python.org/3/library/stdtypes.html#frozenset.intersection

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants