Problem

Merge two given sorted integer array A and B into a new sorted integer array.

Example
A=[1,2,3,4]

B=[2,4,5,6]

return [1,2,2,3,4,4,5,6]

思路

  • 两个指针, a和b
  • 分成三种情况
    • a < lenA && b < lenB
    • a < lenA
    • b < lenB
    public int[] mergeSortedArray(int[] A, int[] B) {
        if (A == null || A.length == 0) {
            return B;
        }
        if (B == null || B.length == 0) {
            return A;
        }

        int aLen = A.length;
        int bLen = B.length;

        int[] ans = new int[aLen + bLen];
        int pa = 0;
        int pb = 0;
        int index = 0;

        while (pa < aLen && pb < bLen) {
            if (A[pa] < B[pb]) {
                ans[index++] = A[pa++]; 
            } else {
                ans[index++] = B[pb++];
            }
        }

        while (pa < aLen) {
            ans[index++] = A[pa++];
        }
        while (pb < bLen) {
            ans[index++] = B[pb++];
        }

        return ans;
    }

results matching ""

    No results matching ""