class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int>v;
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
for(int i=1;i<nums1.size();i )
{
if(nums1[i]==nums1[i-1])
nums1.erase(nums1.begin() i);
}
for(int i=1;i<nums2.size();i )
{
if(nums2[i]==nums2[i-1])
nums2.erase(nums2.begin() i);
}
for(int i=0;i<nums1.size();i )
{
for(int j=0;j<nums2.size();j )
{
if(nums1[i]==nums2[j])
{
v.push_back(nums1[i]);
}
}
}
return v;
}
};
While I am comparing in both the vectors i am trying to erase dublicate elements. But eventually end up in erasing just one dublicate element and not another.The first three lines denotes vector after sorting and last denotes removing of dublicates
CodePudding user response:
In the first 2 loops, you are erasing an element in a
std::vector
, from within a loop traversing its elements. This is a bad idea because thestd::vector
's size and element indices will change. A similar issue arrised when you use iterators which are invalidated by usingerase
. See: std::vector::eraseYou can see here info how to do it correctly: What's the most efficient way to erase duplicates and sort a vector?
intersection
does not access any class members (because there aren't any). It could be made into a free function, or astatic
method of classSolution
(if it makes sense to put it in there).Better to avoid
using namespace std
- see here Why is "using namespace std;" considered bad practice?Please avoid posting images of used data. Instead copy-paste it as text so that it's easy for us to test.