Skip to content

Conversation

@skypenguins
Copy link
Owner

349. Intersection of Two Arrays

次回予告: 617. Merge Two Binary Trees

@skypenguins skypenguins self-assigned this Aug 27, 2025
}
int common = *nums1Pointer;
ans.push_back(common);
while (nums1Pointer != nums1.end() && common == *nums1Pointer) {
Copy link

Choose a reason for hiding this comment

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

sort() したあとに nums1.erase(std::unique(nums1.begin(), nums1.end()), nums1.end()); しておくと、 ++nums1Pointer; するだけで済み、シンプルになると思います。


## Step1
* 入力の長さが最大1000なので、素直な二重ループ $O(n^2)$ でACすると判断
- $約10^8 回/秒$ として、
Copy link

Choose a reason for hiding this comment

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

pythonだと1秒あたり100万ステップ(10^6)程度と見ておくと良いとのことでした。
ichika0615/arai60#8 (comment)

試しに下記をcolab notebookで実行してみたのですが、3,001,858 ops/secとなり、 300万ステップでした。

import time

N = 10_000_000
x = 0
start = time.time()
for i in range(N):
    x += 1
end = time.time()

print(f"{N / (end - start):,.0f} ops/sec")

sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());

auto nums1Pointer = nums1.begin();

Choose a reason for hiding this comment

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

このあたりに倣うなら nums1_pointer でしょうか。
https://google.github.io/styleguide/cppguide.html#Variable_Names


auto nums1Pointer = nums1.begin();
auto nums2Pointer = nums2.begin();
vector<int> ans;

Choose a reason for hiding this comment

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

result などの方がいいでしょうか。後は C++ の名前空間で衝突しないなら intersection などでもいいと思います (軽く見た感じ std::set_intersection なので大丈夫そう)
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.fcs3httrll4l

public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
Copy link

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants