1. 代码
package com.jfp;
import java.util.Arrays;
/**
* @author jiafupeng
* @desc
* @create 2021/3/17 16:59
* @update 2021/3/17 16:59
**/
public class Test4 {
public static int[] merge(int[] arr1, int[] arr2) {
int m = 0;
int n = 0;
int[] mergeArr = new int[arr1.length + arr2.length];
int i = 0;
while (m < arr1.length || n < arr2.length) {
if(m >= arr1.length){
mergeArr[i++] = arr2[n++];
} else if(n >= arr2.length){
mergeArr[i++] = arr1[m++];
} else if(arr1[m] < arr2[n]){
mergeArr[i++] = arr1[m++];
} else {
mergeArr[i++] = arr2[n++];
}
}
return mergeArr;
}
public static void main(String[] args) {
int[] arr1 = {1,3,5,7};
int[] arr2 = {2,4,6,8,10,12};
int[] merge = merge(arr1, arr2);
System.out.println(Arrays.toString(merge));
}
}
2. 输出
[1, 2, 3, 4, 5, 6, 7, 8, 10, 12]
网友评论