Skip to content

349. intersection of two arrays#12

Open
maeken4 wants to merge 3 commits into
mainfrom
349.-Intersection-of-Two-Arrays
Open

349. intersection of two arrays#12
maeken4 wants to merge 3 commits into
mainfrom
349.-Intersection-of-Two-Arrays

Conversation

@maeken4
Copy link
Copy Markdown
Owner

@maeken4 maeken4 commented 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());
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

関数を呼び出す側にとって、関数に渡した値が関数の中で書き換わってしまうことは、通常意図しないことが多いと思います。コピーを作ってからソートしたほうが良いと思います。

なお、業務で書くコードの場合、関数の引数のうち、複合型で値を変更しないものについては、 const 参照で渡すことが多いと思います。また、関数の出力を引数で返す場合は、非 const 参照にすることが多いと思います。
また、一つの引数が入力と出力の両方を兼ねることはあまりないように感じます。何らかの理由によりもしそうする場合は、関数のコメントで明示的に説明すると思います。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コメントありがとうございます。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())
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

入力を std::set に入れてから std::set_intersection() すると、この行が不要になります。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。単純にソートするよりそのほうが簡潔で効率がよさそうですね。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants