Simple Merge in Java with explanation


  • 0
    L

    Imagine an example with different size where nums1 will have enough space to hold the second array. The trick is to start from the end of the given m and n and copy the bigger number from the end to the first.

    public void merge(int[] nums1, int m, int[] nums2, int n) {
            int idx=m+n-1;
            int i=m-1;
            int j=n-1;
            while(i>=0 && j>=0) {
                if(nums1[i] >= nums2[j]) {
                    nums1[idx--] = nums1[i--];
                }
                else {
                    nums1[idx--] = nums2[j--];
                }
            }
            while(j>=0) {
                nums1[idx--] = nums2[j--];
            }
            while(i>=0) {
                nums1[idx--] = nums1[i--];
            }
        }
    

Log in to reply
 

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