Conversation
| nums1 = set(nums1) | ||
| nums2 = set(nums2) |
There was a problem hiding this comment.
すみません、Pythonの場合正確には「参照の値渡し」だったので、この書き方で問題なかったです。
このコメントは無視してください。
| if nums1[i1] == nums2[i2]: | ||
| if nums1[i1] not in seen: | ||
| intersection_of_the_two.append(nums1[i1]) | ||
| seen.add(nums1[i1]) |
There was a problem hiding this comment.
最初にソートしていて同じ値のものは隣合っていることが保証されているので、ポインタをうまく移動させることで重複排除にseenを使わなくても済み、ちょっとメモリを節約できます。
具体的には以下のような感じです。
while i1 < len(nums1) and i2 < len(nums2):
if nums1[i1] == nums2[i2]:
common = nums1[i1]
intersection_of_the_two.append(common)
while i1 < len(nums1) and nums1[i1] == common:
i1 += 1
while i2 < len(nums2) and nums2[i2] == common:
i2 += 1
elif nums1[i1] < nums2[i2]:
i1 += 1
else:
i2 += 1There was a problem hiding this comment.
ソートしているのでseenがなくても重複している値はわかるというのは盲点でした。とてもスッキリした考察ありがとうございます。seen書くのは空間計算量が増えるので結構ためらって書いたので助かります。
| @@ -0,0 +1,3 @@ | |||
| class Solution: | |||
| def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: | |||
| return list(set(nums1) & set(nums2)) | |||
There was a problem hiding this comment.
&でintersection()と同値なことができるのってどうしてなんですか??
operator & を set classがメソッドとして持っていると推測してるのですが、ソースコード見つけれられず
There was a problem hiding this comment.
There was a problem hiding this comment.
operator & を set classがメソッドとして持っていると推測してるのですが<-これであっていると思います。コードは上のCPythonにあります
There was a problem hiding this comment.
なるほど ありがとうございます
__and__って書くんですね(^^ ;) grepしても見つからないわけだ
There was a problem hiding this comment.
There was a problem hiding this comment.
C++ は operator ですね。
https://en.cppreference.com/w/cpp/language/operators
There was a problem hiding this comment.
C++のような文法を予想して探してたのですぐに見つかりませんでした
There was a problem hiding this comment.
Rust は、これですかね?
https://doc.rust-lang.org/std/ops/index.html
There was a problem hiding this comment.
ですです
Note that the && and || operators are currently not supported for overloading. Due to their short circuiting nature, they require a different design from traits for other operators like BitAnd. Designs for them are under discussion.
これは知らなかった。なんでなのか調べるの面白そうですね
問題
349. Intersection of Two Arrays
次解く予定のもの
104. Maximum Depth of Binary Tree
617. Merge Two Binary Trees