JS solution


  • 0
    var merge = function(nums1, m, nums2, n) {
        const trim = (array, m) => {
            if (array.length <= m) return;
    
            // array.length > m, do trim
            const numToPop = array.length - m;
            for (let i = 0; i < numToPop; i++) {
                array.pop();
            }
        };
        
        trim(nums1, m);
        trim(nums2, n);
        
        
        const insert = (num, array, index) => {
            array.splice(index, 0, num);
        };
    
        let i1 = 0, i2 = 0;
        while (i2 < nums2.length && i1 < nums1.length) {
            if (nums1[i1] > nums2[i2]) {
                insert(nums2[i2], nums1, i1);
                i2++;
            }
    
            i1++;
        }
        
        if (i2 < nums2.length) {
            for (i2; i2 < nums2.length; i2++) {
                nums1.push(nums2[i2]);
            }
        }
    };
    

Log in to reply
 

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