Home > Enterprise >  The code is erasing just one dublicates and not another. Why so?
The code is erasing just one dublicates and not another. Why so?

Time:04-29

enter image description here

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:

  1. 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 the std::vector's size and element indices will change. A similar issue arrised when you use iterators which are invalidated by using erase. See: std::vector::erase

  2. You can see here info how to do it correctly: What's the most efficient way to erase duplicates and sort a vector?

  3. intersection does not access any class members (because there aren't any). It could be made into a free function, or a static method of class Solution (if it makes sense to put it in there).

  4. Better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?

  5. Please avoid posting images of used data. Instead copy-paste it as text so that it's easy for us to test.

  •  Tags:  
  • c
  • Related