Search code examples
c++vector2d-vector

What is the error in this code,In 2d vector how the extra elements gets added?


How again -1,2,-1 gets included in the next pair? The question is: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<int>r1;
        vector<vector<int>>resvec;
        int s=nums.size();
        int i=0,j,k=s-1;
        for(;k-i>=2;k--)
        {
            for(j=i+1;j<k;j++)
            {
                if(nums[i]+nums[j]+nums[k]==0)
                {
                    r1.push_back(nums[i]);
                    r1.push_back(nums[j]);
                    r1.push_back(nums[k]); 
                    resvec.push_back(r1);
                }
                
            }
        }
        if(s>=3)
        return resvec;
        else
            return {};
    }
};

I was expecting this output: [[-1,-1,2],[-1,0,1]]

Why it's giving output like this: [[-1,2,-1],[-1,2,-1,-1,0,1]]


Solution

  • You forgot to clear r1 before adding new elemnets.

    if(nums[i]+nums[j]+nums[k]==0)
    {
        r1.clear(); // clear the vector (erase the extra elements)
        r1.push_back(nums[i]);
        r1.push_back(nums[j]);
        r1.push_back(nums[k]); 
        resvec.push_back(r1);
    }
    

    Instead of clearing, you should declare r1 inside the inner if:

    if(nums[i]+nums[j]+nums[k]==0)
    {
        vector<int>r1; // declare here, not top of the function
        r1.push_back(nums[i]);
        r1.push_back(nums[j]);
        r1.push_back(nums[k]); 
        resvec.push_back(r1);
    }
    

    Another way in C++11 or later is constructing the vector to add directly without extra variables:

    if(nums[i]+nums[j]+nums[k]==0)
    {
        resvec.push_back(vector<int>{nums[i], nums[j], nums[k]});
    }