题目描述:
现在有多组整数数组,需要将他们合并成一个新的数组。合并规则,从每个数组里按顺序取出固定长度的内容合并到新的数组中,取完的内容会删除掉,如果该行不足固定长度或者已经为空,则直接取出剩余部分的内容放到新的数组中,继续下一行。如样例1,获得长度3,先遍历第一行,获得2,5,6;再遍历第二行,获得1,7,4;再循环回到第一行,获得7,9,5;再遍历第二行,获得3,4;再回到第一行,获得7,按顺序拼接成最终结果。
输入描述:
第一行是每次读取的固定长度,长度>0;
第2-n行是需要合并的数组,不同的数组用回车换行分隔,数组内部用逗号分隔。
输出描述:
输出一个新的数组,用逗号分隔。
-------------示例---------------------------------------------------------------------------
输入:
3
2,5,6,7,9,5,7
1,7,4,3,4
4,5,7,1,3,8
输出:
2,5,6,1,7,4,4,5,7,7,9,5,3,4,1,3,8,7
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
int num = Integer.parseInt(sc.nextLine());
List<Integer> list1 = Arrays.stream(sc.nextLine().split(",")).map(Integer::parseInt).collect(Collectors.toList());
List<Integer> list2 = Arrays.stream(sc.nextLine().split(",")).map(Integer::parseInt).collect(Collectors.toList());
List<Integer> list3 = Arrays.stream(sc.nextLine().split(",")).map(Integer::parseInt).collect(Collectors.toList());
List<List<Integer>> result1 = get(list1, num);
List<List<Integer>> result2 = get(list2, num);
List<List<Integer>> result3 = get(list3, num);
int maxSize = Math.max(result1.size(), Math.max(result2.size(), result3.size()));
List<Integer> result = new ArrayList<>();
for (int i = 0; i < maxSize; i++) {
if (i < result1.size()) {
result.addAll(result1.get(i));
}
if (i < result2.size()) {
result.addAll(result2.get(i));
}
if (i < result3.size()) {
result.addAll(result3.get(i));
}
}
StringBuilder sb = new StringBuilder();
result.forEach(o -> sb.append(o).append(","));
System.out.println(sb.substring(0, sb.length() - 1));
}
}
private static List<List<Integer>> get(List<Integer> list, Integer num) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < list.size(); i += num) {
if (i + num <= list.size()) {
result.add(list.subList(i, i + num));
}
if (i + num > list.size()) {
result.add(list.subList(i, list.size()));
break;
}
}
return result;
}
输出结果: