自己练习用,非提交代码
将两个有序整数组合并成一个新的有序整数组
输入四行:
整数组nums1
nums1的长度m
整数组nums2
nums2的长度n
输出一行:
合并后的新数组
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* 合并两个数组
* */
public class arrayCombine {
public static void main(String[] args)throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// 获取输入
String [] nums1 = bf.readLine().replace("]","").replace("[","").split(",");
int m = Integer.parseInt(bf.readLine());
String [] nums2 = bf.readLine().replace("]","").replace("[","").split(",");
int n = Integer.parseInt(bf.readLine());
// 初始化合成后的数组
int[] ret = new int[m + n];
StringBuilder sb = new StringBuilder();
for(int i = 0; i < m; i++){
sb.append(nums1[i]);
if (i < m-1)
sb.append(",");
}
if (n != 0 ) sb.append(",");
for (int j = 0; j < n; j++){
sb.append(nums2[j]);
if (j < n-1)
sb.append(",");
}
// 获得合并后的字符串
String[] s = sb.toString().replace("[","").replace("]","").split(",");
sb.setLength(0);
sb.append("[");
for (int k = 0; k < ret.length; k++){
ret[k] = Integer.parseInt(s[k]);
}
// 排序
Arrays.sort(ret);
for (int l = 0; l < ret.length; l++){
sb.append(ret[l]);
if (l < ret.length - 1)
sb.append(",");
}
sb.append("]");
System.out.print(sb);
sb.setLength(0);
}
}
测试效果