349. intersection of two arrays#12
Open
maeken4 wants to merge 3 commits into
Open
Conversation
nodchip
reviewed
Jul 21, 2025
| public: | ||
| std::vector<int> intersection(std::vector<int>& nums1, std::vector<int>& nums2) { | ||
| std::vector<int> result; | ||
| std::sort(nums1.begin(), nums1.end()); |
There was a problem hiding this comment.
関数を呼び出す側にとって、関数に渡した値が関数の中で書き換わってしまうことは、通常意図しないことが多いと思います。コピーを作ってからソートしたほうが良いと思います。
なお、業務で書くコードの場合、関数の引数のうち、複合型で値を変更しないものについては、 const 参照で渡すことが多いと思います。また、関数の出力を引数で返す場合は、非 const 参照にすることが多いと思います。
また、一つの引数が入力と出力の両方を兼ねることはあまりないように感じます。何らかの理由によりもしそうする場合は、関数のコメントで明示的に説明すると思います。
Owner
Author
There was a problem hiding this comment.
コメントありがとうございます。Leetcodeの形式をそのままコピーしてしまっていました。意識するようにします。
確かに確認してみるとstd::vector::push_backなども引数はconst参照になっていました。
| std::sort(nums2.begin(), nums2.end()); | ||
|
|
||
| std::set_intersection(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), std::back_inserter(result)); | ||
| result.erase(std::unique(result.begin(), result.end()), result.end()) |
There was a problem hiding this comment.
入力を std::set に入れてから std::set_intersection() すると、この行が不要になります。
Owner
Author
There was a problem hiding this comment.
ありがとうございます。単純にソートするよりそのほうが簡潔で効率がよさそうですね。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This Problem
https://leetcode.com/problems/intersection-of-two-arrays/description/