349. Intersection of Two Arrays#13
Conversation
| 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() |
There was a problem hiding this comment.
関数名と変数名を同一にすると、再帰ができなくなるなど弊害があるので避ける癖があると良いと思います。
| sorted_nums2 = sorted(nums2) | ||
| i = 0 | ||
| j = 0 | ||
| result = set() |
There was a problem hiding this comment.
関数名で何をするかは分かると思いますが、result の命名は読み手の負荷を下げる練習として分かりやすい命名にしてもいいのかなと思います。今回は、common_numsとかはどうでしょうか。
また、set なので、while で数字の繰り返しを避ける処理は不要になると思います。whileで処理を飛ばしたい場合は、list の方が意図が分かりやすいのではないでしょうか。
There was a problem hiding this comment.
また、set なので、while で数字の繰り返しを避ける処理は不要になると思います。whileで処理を飛ばしたい場合は、list の方が意図が分かりやすいのではないでしょうか。
なるほどですね。確かに、今の実装ではresultに要素を追加する時に、要素は被り得ないのでlistでも実装できましたね。
ご指摘ありがとうございます。
| num1 = sorted_nums1[i] | ||
| num2 = sorted_nums2[j] | ||
| if num1 == num2: | ||
| if num1 not in intersection: |
There was a problem hiding this comment.
set() は、すでに含まれている値を add() で挿入しようとしても、内容が変わりません。そのため、この if 文は省いても同じ結果になると思います。一方、if 文を省くと、同じ値を複数回 add() するというコードになり、読み手にとって意図が分かりづらいコードになるかもしれません。悩ましい所です。
| if num1 < num2: | ||
| i += 1 | ||
| continue | ||
| elif num1 > num2: |
There was a problem hiding this comment.
elif は if としても良いと思います。自分なら continue と次の行のあいだに空行を入れ、各 if 文を一つの塊として視覚的に認識しやすくし、読み手に一塊の処理であることを伝えるよう書くと思います。趣味の範囲だと思います。
この問題: Intersection of Two Arrays
次の問題: Unique Email Addresses