Difficulty: Easy

Merge nums2 into nums1 to make nums1 an ordered array.

Initialize nums1 and nums2 to m and n, respectively. You can assume that nums1 has a space size equal to m + n so that it has enough space to hold elements from Nums2.

Their thinking

Since nums1 has a length of m + n, sort from nums1 to nums1.

Answer key

public void mergeReverseDoublePointer(int[] nums1, int m, int[] nums2, int n) {
    int index1 = m - 1;
    int index2 = n - 1;
    int tailIndex = m + n - 1;
    int current;
    while (index1 >= 0 || index2 >= 0) {
        if (index1 < 0) {
            current = nums2[index2--];
        } else if (index2 < 0) {
            current = nums1[index1--];
        } else if (nums1[index1] < nums2[index2]) {
            current = nums2[index2--];
        } else{ current = nums1[index1--]; } nums1[tailIndex--] = current; }}Copy the code

test

@Test
public void test_reverseDoublePointer_case1(a) {
    int[] nums1 = {1.2.3.0.0.0};
    mergeSortedArray.mergeReverseDoublePointer(nums1, 3.new int[] {2.5.6}, 3);
    Assertions.assertArrayEquals(new int[] {1.2.2.3.5.6}, nums1);
}

@Test
public void test_reverseDoublePointer_case2(a) {
    int[] nums1 = {1};
    mergeSortedArray.mergeReverseDoublePointer(nums1, 1.new int[] {},0);
    Assertions.assertArrayEquals(new int[] {1}, nums1);
}

@Test
public void test_reverseDoublePointer_case3(a) {
    int[] nums1 = {4.5.6.0.0.0};
    mergeSortedArray.mergeReverseDoublePointer(nums1, 3.new int[] {1.2.3}, 3);
    Assertions.assertArrayEquals(new int[] {1.2.3.4.5.6}, nums1);
}
Copy the code