2018-09-15 11:35:10 +00:00
|
|
|
# [350. Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/description/)
|
|
|
|
# 思路
|
|
|
|
基本同[349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/description/), 只是题结果中可以出现重复元素,
|
|
|
|
则先对两个数组进行排序,然后再用两个指针遍历一遍数组,合理更新指针即可获得两个数组的相同元素。
|
|
|
|
时间复杂度O(nlogn)
|
|
|
|
# C++
|
2019-09-13 15:08:41 +00:00
|
|
|
```C++
|
2018-09-15 11:35:10 +00:00
|
|
|
class Solution {
|
|
|
|
public:
|
|
|
|
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
|
|
|
|
sort(nums1.begin(), nums1.end());
|
|
|
|
sort(nums2.begin(), nums2.end());
|
|
|
|
vector<int>res;
|
|
|
|
int p1 = 0, p2 = 0;
|
|
|
|
while(p1 < nums1.size() && p2 < nums2.size()){
|
|
|
|
if(nums1[p1] < nums2[p2]) p1++;
|
|
|
|
else if(nums1[p1] > nums2[p2]) p2++;
|
|
|
|
else{
|
|
|
|
res.push_back(nums1[p1]);
|
|
|
|
p1++;
|
|
|
|
p2++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
```
|