from rear to front adding element to avoid change the current value


  • 0
    R

    public void merge(int[] nums1, int m, int[] nums2, int n) {
    // from right position begin and then reduce one by one
    int i1 = m-1;
    int i2 = n-1;
    int curr = m+n-1;
    while (i1 >= 0 && i2 >= 0) {
    nums1[curr--] = nums1[i1] < nums2[i2] ? nums2[i2--] : nums1[i1--];
    //i1++;
    //i2++;
    }
    while (i1 >= 0) {
    nums1[curr--] = nums1[i1--];
    //i1++;
    }
    while (i2 >= 0) {
    nums1[curr--] = nums2[i2--];
    //i2++;
    }
    }


Log in to reply
 

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