Conversation
問題文URL: https://leetcode.com/problems/intersection-of-two-arrays/description/ Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
| if nums1[index_1] > nums2[index_2]: | ||
| index_2 += 1 | ||
| continue | ||
| common.add(nums1[index_1]) |
There was a problem hiding this comment.
両方に、例えば5が2つずつ入っていたら、2回 add されるの一応気になります。(set にいれているので、結果的には問題ないわけですが、本当は list への追記にすることもできて、そうすると最後の list へのキャストが省略できますよね。)
There was a problem hiding this comment.
これ、反応として気になるなという感じなんですね。ありがとうございます。
後でlistのバージョンで実装してみます
| index_2 = 0 | ||
| nums1 = sorted(nums1) | ||
| nums2 = sorted(nums2) | ||
| common = set() |
| ``` | ||
|
|
||
| - 片方を、dict か set にする | ||
| - 変数名、elementとか回りくどく説明しなくても、これくらいならnumでもいいかも、となんとなく思う |
| def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: | ||
| nums2 = set(nums2) | ||
| common = set() | ||
| for element_1 in nums1: |
There was a problem hiding this comment.
grep.app でPythonに絞って検索したら、num_1が734件、num1が3180件なので、underscoreつけないのがむしろ一般的なのかもしれないですね。
liquo_riceさんなら、こういうことを調べる時どこで調べますか?
There was a problem hiding this comment.
https://source.chromium.org/ や https://cs.opensource.google/ ですかね。underscoreは単語の区切りを明確にするためのものだとみなすと、数字の前後には不要な気がします。
There was a problem hiding this comment.
おお、このようなページがあるんですね、ありがとうございます。
数字の前後には不要な気がします。
確かにそうですね。num2ではなく、num_twoのような表記だったらあっても良さそうです
| unique_nums1 = set(nums1) | ||
| unique_nums2 = set(nums2) | ||
| return list(unique_nums1 & unique_nums2) |
There was a problem hiding this comment.
無理に変数に入れずに
return list(set(nums1) & set(nums2))みたいにしてしまってもいいかもですね。
There was a problem hiding this comment.
その選択肢は思いついてなかったです。ありがとうございます。
| ```python | ||
| class Solution: | ||
| def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: | ||
| nums2 = set(nums2) | ||
| common = set() | ||
| for num in nums1: | ||
| if num in nums2: | ||
| common.add(num) | ||
| return list(common) |
There was a problem hiding this comment.
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums2 = set(nums2)
common = []
for num in nums1:
if num in nums2 and num not in common:
common.append(num)
return common(他の選択肢として)このようにすればcommonを最初からlistでいけますね。
There was a problem hiding this comment.
なるほどそうですね、ありがとうございます
みなさんのコメントを見てて思うんですが、setに変換したりlistに変換したりするのって意外と抵抗があるものなんですね
問題文URL: https://leetcode.com/problems/intersection-of-two-arrays/description/
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.