Skip to content

349. Intersection of Two Arrays#13

Open
rimokem wants to merge 1 commit into
mainfrom
0349-intersection-of-two-arrays
Open

349. Intersection of Two Arrays#13
rimokem wants to merge 1 commit into
mainfrom
0349-intersection-of-two-arrays

Conversation

@rimokem
Copy link
Copy Markdown
Owner

@rimokem rimokem commented Apr 5, 2026

Comment thread 0349/memo.md
- `other`が集合でないときは、`other`をイテレーションしてハッシュ探索を行う。
- `set`が`other`より短いとき、共通要素が`set`のサイズに達した時点でループを早期終了する。

- "片方がとても大きくて、片方がとても小さいときには、大きい方を set にするのは大変じゃないでしょうか"という話があった。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

こちらでは、どのような「大変さ」を想定していますか?

set への変換に伴うメモリ使用量を問題とするのであれば、「小さい方を set にする」という解法とは結びつかないので、実行時間ですかね?

もし、大きい配列を set に変換する際の実行時間を問題とするのであれば、大きい配列に対して線形探索を行うことは避けたくなります。たしかに早期終了の可能性はありますが、小さい配列をイテレーションすれば確実に早期終了します。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

「大変さ」としてはsetへの変換に伴うメモリ使用量を想定しています。

"片方がとても大きくて、片方がとても小さい"という状況なので、小さい方だけsetに変換し、大きい方はそのままにしています。
これで、空間計算量をO(n+m)からO(min(n,m))に減らせると考えて実装しました。

min(n,m) << n+m なので、上記の状況だと空間計算量の問題を解決できていると考えています。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ありがとうございます。よくわかりました。

あとは、katataku/leetcode#12 (comment)
にある二分探索を使う方法と比べて、どういうときにどちらが実行時間が短いかなど考えてみてもいいかもしれません。

Comment thread 0349/step3.py
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
return list(set(nums1).intersection(nums2))
Copy link
Copy Markdown

@h-masder h-masder Apr 7, 2026

Choose a reason for hiding this comment

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

今回の問題はインターセクションを求めること自体がテーマだと思うので、intersection をそのまま用いる解法は、やや問題の意図とは異なる可能性もあるかなと感じました。
そのため、別のアプローチ(例えば基本的な操作で解く方法)も併せて示せると、より理解が深まると思います。
一方で、intersection の仕様や挙動に触れている点はとても良いと思います。

Copy link
Copy Markdown
Owner Author

@rimokem rimokem Apr 7, 2026

Choose a reason for hiding this comment

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

レビューありがとうございます。

元はコーディング面接の問題であることが、頭から抜けていました。
いざ出題されたときにこれを出すのは、流石に意図を無視していますね。

後に色々聞かれるのでしょうが、一発目に出すコードとしては以下を思い付きました。

 def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums1_set = set(nums1)
        nums2_set = set(nums2)
        result = []
        for n in nums1_set:
            if n in nums2_set:
                result.append(n)
        return result

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.

2 participants