归并两个有序数组

题目描述:给定两个有序数组,把两个给定的数组合并成一个新的数组,新的数组仍然保持有序。

代码如下:

public class DoublePointer {
    public static void main(String[] args){
        int[] arr1 = {2,3,5,8,9,12,15,21};
        int[] arr2 = {1,4,6,7,10,11,17};
        print(merge(arr1, arr1.length, arr2, arr2.length));
    }

    public static int[] merge(int[] nums1, int m, int[] nums2, int n) {
        int index1 = m - 1, index2 = n - 1;
        int indexMerge = m + n - 1;
        int[] arr = new int[m + n];

        while (index1 >= 0 || index2 >= 0) {
            if (index1 < 0) {
                arr[indexMerge--] = nums2[index2--];
            } else if (index2 < 0) {
                arr[indexMerge--] = nums1[index1--];
            } else if (nums1[index1] > nums2[index2]) {
                arr[indexMerge--] = nums1[index1--];
            } else {
                arr[indexMerge--] = nums2[index2--];
            }
        }
        return arr;
    }
    
    public static void print(int[] arr){
        System.out.print("[");
        for (int i = 0; i < arr.length; i++){
            if (i!=arr.length-1){
                System.out.print(arr[i] + ",");
            }else{
                System.out.print(arr[i]);
            }

        }
        System.out.print("]");
    }
}

执行结果:[1,2,3,4,5,6,7,8,9,10,11,12,15,17,21]

posted @ 2018-12-05 15:13  earth_houge  阅读(340)  评论(0编辑  收藏  举报