LintCode - 合并排序数组(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

合并两个排序的整数数组A和B变成一个新的数组。

样例
给出A=[1,2,3,4],B=[2,4,5,6],返回** [1,2,2,3,4,4,5,6]**

思路:归并排序

  /**
     * @param A and B: sorted integer array A and B.
     * @return: A new sorted integer array
     */
    public int[] mergeSortedArray(int[] A, int[] B) {
        int[] tmp = new int[A.length + B.length];    
        int tmpPos = 0;
        int aPos = 0;
        int aEnd = A.length - 1;
        int bPos = 0;
        int bEnd = B.length - 1; 
        while(aPos <= aEnd && bPos <= bEnd){
            if(A[aPos] < B[bPos]){
                tmp[tmpPos++] = A[aPos++];
            }else{
                tmp[tmpPos++] = B[bPos++];
            }
        }      
        while(aPos <= aEnd){
            tmp[tmpPos++] = A[aPos++];
        }        
        while(bPos <= bEnd){
            tmp[tmpPos++] = B[bPos++];
        }        
        return tmp;
    }

你可能感兴趣的:(LintCode - 合并排序数组(普通))