My solution in C++ (7ms)


  • 4
    D

    A concise version is

    class Solution {
    public:
        void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
            int wrtPt = m-- + n-- ;
            while(n>=0)
            {
                if(m<0 || (nums1[m]<nums2[n]) ) nums1[--wrtPt] = nums2[n--];
                else nums1[--wrtPt] = nums1[m--];
            }
        }
    };
    

    The original one is as below

    class Solution {
    public:
        void merge(int A[], int m, int B[], int n) {
            int i=m-1;
            int j;
            for(j=n-1;j>=0;j--)
            {
                while( (i>=0) && (A[i]>=B[j]))
                {
                    A[i+j+1] = A[i];
                    i--;
                }
                A[i+j+1] = B[j];
            }
        }
    };
    

    You have to insert B to A starting from the end, it only moves A elements when necessary.


Log in to reply
 

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