简单题6-合并排序数组 II

描述

合并两个排序的整数数组A和B变成一个新的数组。
您在真实的面试中是否遇到过这个题? 是
样例

给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
挑战

你能否优化你的算法,如果其中一个数组很大而另一个数组很小?
【思路】
数组已经是排好序,申请一个合并后数组大小的数组,开始比较两个数组中的大小遍历赋值给要合并的数组,如果一个数组遍历完了,另一个数组还没有遍历结束,就直接把没有遍历完的数组中的元素赋值给合并的数组中。
【代码实现】

package 数组和矩阵;

public class Main4 {

    public static void main(String[] args) {
        int[] a = { 1, 2, 3, 4 };
        int[] b = { 2, 4, 5, 6 };

        int[] result = mergeSortedArray(a, b);
        print(result);

    }

    private static void print(int[] result) {
        for (int i = 0; i < result.length; i++) {
            System.out.print(result[i] + " ");
        }
        System.out.println();

    }

    public static int[] mergeSortedArray(int[] A, int[] B) {
        int[] result = new int[A.length + B.length];

        int cur = 0;
        int i = 0;
        int j = 0;
        while (i < A.length && j < B.length) {
            if (A[i] <= B[j]) {
                result[cur++] = A[i];
                i++;
            } else {
                result[cur++] = B[j];
                j++;
            }
        }
        while (j <= B.length - 1) {
            result[cur++] = B[j++];
        }
        while (i <= A.length - 1) {
            result[cur++] = A[i++];
        }

        return result;
    }

}

你可能感兴趣的:(简单题6-合并排序数组 II)