How to use insert() method of vector to solve this problem? waiting online, anxious!


  • 0
    1

    It seems all the solutions are based on value-swapped, so I wonder if it can be solved by the embedded method insert() of vector?


  • 0
    C

    I don't really enjoy the solution , spent a lot time on debugging :(

    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    		int i = 0;
    		nums1.erase(nums1.begin() + m, nums1.end());
    
    		if (m == 0)
    		{
    			for (int sz = 0; sz < n; ++sz)
    			{
    				nums1.push_back(nums2[sz]);
    			}
    
    			return;
    		}
    
    		for (int j = 0; j < n; )
    		{
    			for (; i < nums1.size() && j < nums2.size();)
    			{
    				if (nums2[j] < nums1[i])
    				{
    					nums1.insert(nums1.begin() + i, nums2[j]);
    					++j;
    				}
    				
    				++i;
    			}
    
    			if (i >= nums1.size() - 1 && j < n)
    			{
    				for (;j<n;)
    				{
    					nums1.insert(nums1.begin() + i++, nums2[j++]);
    				}
    				
    			}
    		}
    	}

Log in to reply
 

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