Conversation
| - https://stackoverflow.com/questions/19907677/whats-the-difference-between-iterator-and-back-insert-iterator#:~:text=see%20the%20following-,(adaptor)%20iterators,-%3A | ||
|
|
||
| ## step3 | ||
| - 補完無しで2分弱ほどで実装する。 |
There was a problem hiding this comment.
このような議論もありました
katataku/leetcode#12 (comment)
There was a problem hiding this comment.
共有していただきありがとうございます。
片方をソートする場合、引数をサイズが小さい配列と大きい配列に分け、小さい方をソートする方法を考えました。
(下で提案していただいた方法であれば、大きい配列を全探索する計算が一度で済みます。)
確かに、条件を変えたときに案があまり出てきませんでした。
そして、そもそも出題意図を推定する発想がありませんでした。
考えます。
| } | ||
| return intersected_nums; | ||
| } | ||
| }; |
There was a problem hiding this comment.
- seen_in_nums1 を作る
- nums2を走査し、seen_in_nums1に含まれるものがあればintersected_numsに追加し、seen_in_nums1から削除する
というアルゴリズムも考えられます
There was a problem hiding this comment.
ありがとうございます。
そのとき seen_in_nums1 が名前から想起される役割をしなくなってしまいました。
そして、代わりの変数名が思いつかなかったため諦めました。
(メモに書くべきでしたすいません。。)
何か良い変数名はありますでしょうか。
There was a problem hiding this comment.
nums1_not_in_nums2 しか思いつかないですが、なんか不恰好ですね、、
There was a problem hiding this comment.
not_inの発想はなかったです。
ありがとうございます。
| public: | ||
| std::vector<int> intersection(std::vector<int>& nums1, std::vector<int>& nums2) { | ||
| std::set<int> seen_in_nums1; | ||
| std::set<int> seen_in_nums2; |
There was a problem hiding this comment.
この変数はseen_in_num2よりはaddedみたいな名前のほうが挙動と名前の距離が近くてわかりやすくなりそうと思いました。
更に付け加えると宣言場所と利用場所が遠いので、近づけるとこの変数は今から使うということを明示できるので読みやすくなります。
There was a problem hiding this comment.
ありがとうございます。
added とはどのような挙動を表現したものでしょうか。
宣言場所、非常に納得しました。
次から近づけるようにします。
There was a problem hiding this comment.
addedとはどのような挙動を表現したものでしょうか
「最後にreturnするvectorへ追加済であること」の追加済を意味するaddedです。
There was a problem hiding this comment.
added_to_intersected_nums のような命名と解釈しました。
確かに、 その方がカード条件の意味が明確です。
お答えいただきありがとうございます。
| std::set<int> seen_in_nums1; | ||
| std::set<int> seen_in_nums2; | ||
| for (int num : nums1) { | ||
| seen_in_nums1.insert(num); |
There was a problem hiding this comment.
これ、コンストラクタでできませんでしたっけ。.begin(), .end() を渡すと。
| - C++03 から `std::set_intersection` がある。 | ||
| - `std::unordered_set` だと Wrong Answer になる。 | ||
| - ソートしていない場合は未定義動作とある。(つまり何が起きても構わない。) | ||
| - https://en.cppreference.com/w/cpp/algorithm/set_intersection#:~:text=range%2C%20preserving%20order.-,1),-If |
There was a problem hiding this comment.
set_intersection の実装は見ておいてください。
マージソート的な書き方はなんとなく頭にあります。
メモリーに乗らないくらい巨大でも、ソートされているならば、両方から取り出して、小さい方を進めていき、同じだったらそれを確保するということです。
誰か書いていたと思いますね。
問題へのリンク
Intersection of Two Arrays
次に解く問題
Unique Email Addresses