其他分享
首页 > 其他分享> > 合并两个有序数组

合并两个有序数组

作者:互联网

public static int[] mergeTwoArray(int[] arr1, int[] arr2) {

    int i = 0;
    int j = 0;
    int k = 0;
    int len1 = arr1.length;
    int len2 = arr2.length;
    int[] res = new int[len1 + len2];

    while (i < len1 && i < len2) {
        if (arr1[i] <= arr2[j]) {
            res[k++] = arr1[i++];
        } else {
            res[k++] = arr2[j++];
        }
    }

    while (i < len1) {
        res[k++] = arr1[i++];
    }
    while (j < len2) {
        res[k++] = arr2[j++];
    }
    return res;

}

public static void main(String[] args) {
    int[] arr1 = {1, 2, 3, 5};
    int[] arr2 = {2, 4, 6};
    System.out.println(Arrays.toString(arr1));
    System.out.println(Arrays.toString(arr2));
    System.out.println(Arrays.toString(mergeTwoArray(arr1, arr2)));


}
 

标签:数组,len2,int,res,合并,++,arr2,有序,arr1
来源: https://blog.csdn.net/qq_32370249/article/details/119812385