Merge Sorted Array C++ Code fails to pass, using iterator


  • 0
    M
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    
        auto it1=nums1.begin(), it2=nums2.begin();
    
        while(it1!=nums1.end() && it2!=nums2.end())
        {
            if(*it1>*it2)
            {
                it1=nums1.insert(it1,*it2);
                ++it2;
            }
            else
            {
                ++it1;
            }
        }
        
        while(it2!=nums2.end())
        {
            nums1.push_back(*it2);
            ++it2;
        }
        
    }
    

    Failed to pass.

    Input: [0], 0, [1], 1
    Output: [0,1]
    Expected: [1]

    I'm confused about the [0] in the input... Can anyone help me with this problem?


  • 0
    C

    Well you do not want to do insert, since you are asked to assume that nums1 is already big enough for (m+n). This is why they give you m and n separately, instead of reading nums1.size().

    The [0] in the input with m=0 means that nums1 really has no numbers, but there is enough space for (m+n) = (0+1) = 1 number. That space in nums1 happens to be 0, but it doesnt mean that nums1 has a 0 in it (since m=0, it has no numbers in it).

    This part confused me as well, and my first solution was similarly wrong. :)


  • 2
    C

    Oops, posting as answer instead of comment:

    Well you do not want to do insert, since you are asked to assume that nums1 is already big enough for (m+n). This is why they give you m and n separately, instead of reading nums1.size().

    The [0] in the input with m=0 means that nums1 really has no numbers, but there is enough space for (m+n) = (0+1) = 1 number. That space in nums1 happens to be 0, but it doesnt mean that nums1 has a 0 in it (since m=0, it has no numbers in it).

    This part confused me as well, and my first solution was similarly wrong. :)


  • 0
    Z

    thanks for you


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.