6.Merge Two Sorted Arrays

1.Description(Easy)

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]

2.Code

正向扫描

跟Merge two sorted list 相似。

public int[] mergeSortedArray(int[] A, int[] B) {
        int[] result=new int[A.length+B.length];
        int indexA=0;
        int indexB=0;
        int index=0;
        while(indexA<A.length && indexB<B.length){
            if(A[indexA]<=B[indexB]){
                result[index]=A[indexA];
                indexA++;
            }else{
                result[index]=B[indexB];
                indexB++;
            }
            index++;
        }
        while(indexA<A.length){
            result[index]=A[indexA];
            indexA++;
            index++;
        }
        while(indexB<B.length){
            result[index]=B[indexB];
            indexB++;
            index++;
        }
        return result;
    }

Last updated