mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
1000 B
1000 B
350. Intersection of Two Arrays II
思路
基本同349. Intersection of Two Arrays, 只是题结果中可以出现重复元素,
则先对两个数组进行排序,然后再用两个指针遍历一遍数组,合理更新指针即可获得两个数组的相同元素。
时间复杂度O(nlogn)
C++
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;
}
};