【Arai60】13問目 349_Intersection of Two Arrays#13
Conversation
| def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: | ||
| nums1_set = set(nums1) | ||
| intersection = [] | ||
| for num in nums1_set: |
There was a problem hiding this comment.
変数名をnumの代わりにnum1とかにした方がnumという一般的な変数がnums由来ではなくnums1由来であることを別途覚えておく必要がなく読みやすい気がしました。
| intersection = [] | ||
| i = 0 | ||
| j = 0 | ||
| while i < len(nums1) and j < len(nums2): |
There was a problem hiding this comment.
whileの中は素直にif elif elseで良いと思います。例外が2ケースと本命が1ケースあるというより同じレベルの処理が3ケースあるみたいな感じだと思います。
There was a problem hiding this comment.
綺麗に3ケースに分かれるので、その書き方のほうがいいかもしれませんね。
自然言語で説明する場合は、そのようにするので流れとしては自然ですね。
|
Odaさんのコメントを転記 if num in nums2:
if nums1_sorted[i] not in intersection:このあたりです。 特に後ろの、not in は何をやっているのか分からなくなる印象を受けるので、ちょっと作り直してみましょう。 私は、この場合は、結構強く if continue を勧めます。 if A:
B
elif C:
D
else E:
F
Gという形は、B を読んだ後に、G があるかどうかを確認させているからです。 一般に、early return pattern などといいます。 if nums1_sorted[i] == nums2_sorted[j]:これは書きません。 ただ、nan というのがあって、nan == nan が False です。 |
|
Odaさんのコメントを転記 |
問題
https://leetcode.com/problems/intersection-of-two-arrays/