Merge Two Sorted Arrays

ID: 6; easy

Solution 1 (Java)

public class Solution {
    /**
     * @param A: sorted integer array A
     * @param B: sorted integer array B
     * @return: A new sorted integer array
     */
    public int[] mergeSortedArray(int[] A, int[] B) {
        if (A == null) return B;
        if (B == null) return A;

        int[] ans = new int[A.length + B.length];
        int i = 0, j = 0, k = 0;
        while (i < A.length && j < B.length) {
            ans[k++] = A[i] < B[j] ? A[i++] : B[j++];
        }
        while (i < A.length) {
            ans[k++] = A[i++];
        }
        while (j < B.length) {
            ans[k++] = B[j++];
        }

        return ans;
    }
}

Solution 2 (Java)

Solution 3 (Java)

Notes

  • This solution is to handle the challenge: How can you optimize your algorithm if one array is very large and the other is very small?

Last updated

Was this helpful?