package buildingblock.sorting.merge.lc088_mergesortedarray;

/**
 * Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
 * Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
 * The number of elements initialized in nums1 and nums2 are m and n respectively.
 */
public class Solution {

    public void merge(int[] A, int m, int[] B, int n) {
        for (int i = m - 1, j = n - 1, k = m + n - 1; j >= 0; k--) { // terminate if A empty
            A[k] = (i >= 0 && A[i] > B[j]) ? A[i--] : B[j--]; // Pick larger from B or A is empty
        }
    }

    // My 3AC. O(max(M,N)) time. Terminate early if nums2 reach end.
    // Otherwise, pick nums2 if nums1 reach end or nums2 is larger.
    public void merge3(int[] nums1, int m, int[] nums2, int n) {
        for (int i = m - 1, j = n - 1, k = m + n - 1; k >= 0 && j >= 0; k--)
            nums1[k] = (i < 0 || nums1[i] < nums2[j]) ? nums2[j--] : nums1[i--];
    }

    // Too crazy...
    public void merge22(int[] nums1, int m, int[] nums2, int n) {
        while (n > 0) {
            nums1[m + n - 1] = (m == 0 || nums2[n - 1] > nums1[m - 1]) ? nums2[--n] : nums1[--m];
        }
    }

    // My 2nd: idea is good, but it could have been simpler
    public void merge21(int[] nums1, int m, int[] nums2, int n) {
        for (int i = m - 1, j = n - 1, k = m + n - 1; k >= 0; k--) {
            int n1 = (i >= 0) ? nums1[i] : Integer.MIN_VALUE;
            int n2 = (j >= 0) ? nums2[j] : Integer.MIN_VALUE;
            nums1[k] = (n1 > n2) ? nums1[i--] : nums2[j--];
        }
    }

    // My 1st: not elegant
    public void merge1(int[] nums1, int m, int[] nums2, int n) {
        int i = m - 1, j = n - 1, k = m + n - 1;
        while (i >= 0 && j >= 0) {
            nums1[k--] = (nums1[i] > nums2[j]) ? nums1[i--] : nums2[j--];
        }

        while (j >= 0) {
            nums1[k--] = nums2[j--];
        }
    }

}

@@ -403,33 +403,590 @@
  %7B%0A%0A    
-public void merge
+// %5B%5D,%5B%5D  %5B1%5D,%5B%5D  %5B1,2,3%5D,%5B2%5D  %5B1,2,3%5D,%5B0%5D%0A    public void merge(int%5B%5D nums1, int m, int%5B%5D nums2, int n) %7B%0A        if (nums1.length == 0 %7C%7C nums2.length == 0 %7C%7C nums1.length %3C m + n) return;%0A        // Merge nums1 and nums2 to the back of nums1%0A        int i = m - 1, j = n - 1;%0A        for (int k = m + n - 1; i %3E= 0 && j %3E= 0; k--) %7B%0A            nums1%5Bk%5D = nums1%5Bi%5D %3E nums2%5Bj%5D ? nums1%5Bi--%5D : nums2%5Bj--%5D;%0A        %7D%0A        // Copy remaining elts in nums2 to nums1%0A        if (j %3E= 0) System.arraycopy(nums2, 0, nums1, 0, j + 1);%0A    %7D%0A%0A    // Concise%0A    public void merge4
 (int%5B%5D A

merge sorted array