合并两个有序数组

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)));


}
 

上一篇:海伦公式与婆罗摩笈多公式


下一篇:day04