Skip to content

349. Intersection of Two Arrays#13

Open
tNita wants to merge 1 commit into
mainfrom
349_intersection_of_two_arrays
Open

349. Intersection of Two Arrays#13
tNita wants to merge 1 commit into
mainfrom
349_intersection_of_two_arrays

Conversation

@tNita
Copy link
Copy Markdown
Owner

@tNita tNita commented Mar 8, 2026

@tNita tNita changed the title docs: add memo for 349. Intersection of Two Arrays 349. Intersection of Two Arrays Mar 8, 2026
Comment on lines +22 to +27
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
sorted_nums1 = sorted(nums1)
sorted_nums2 = sorted(nums2)
i = 0
j = 0
intersection = 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.

関数名と変数名を同一にすると、再帰ができなくなるなど弊害があるので避ける癖があると良いと思います。

sorted_nums2 = sorted(nums2)
i = 0
j = 0
result = 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.

関数名で何をするかは分かると思いますが、result の命名は読み手の負荷を下げる練習として分かりやすい命名にしてもいいのかなと思います。今回は、common_numsとかはどうでしょうか。
また、set なので、while で数字の繰り返しを避ける処理は不要になると思います。whileで処理を飛ばしたい場合は、list の方が意図が分かりやすいのではないでしょうか。

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 なので、while で数字の繰り返しを避ける処理は不要になると思います。whileで処理を飛ばしたい場合は、list の方が意図が分かりやすいのではないでしょうか。

なるほどですね。確かに、今の実装ではresultに要素を追加する時に、要素は被り得ないのでlistでも実装できましたね。

ご指摘ありがとうございます。

num1 = sorted_nums1[i]
num2 = sorted_nums2[j]
if num1 == num2:
if num1 not in intersection:
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() は、すでに含まれている値を add() で挿入しようとしても、内容が変わりません。そのため、この if 文は省いても同じ結果になると思います。一方、if 文を省くと、同じ値を複数回 add() するというコードになり、読み手にとって意図が分かりづらいコードになるかもしれません。悩ましい所です。

if num1 < num2:
i += 1
continue
elif num1 > num2:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

elif は if としても良いと思います。自分なら continue と次の行のあいだに空行を入れ、各 if 文を一つの塊として視覚的に認識しやすくし、読み手に一塊の処理であることを伝えるよう書くと思います。趣味の範囲だと思います。

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.

3 participants