- 题目描述:
- 现在有多组整数数组,需要将他们合并成一个新的数组。
- 合并规则,从每个数组里按顺序取出固定长度的内容合并到新的数组中,取完的内容会删除掉,
- 如果该行不足固定长度或者已经为空,则直接取出剩余部分的内容放到新的数组中,继续下一行。
- 如样例1,获得长度3,先遍历第一行,获得2,5,6;再遍历第二行,获得1,7,4;
- 再循环回到第一行,获得7,9,5;再遍历第二行,获得3,4;再回到第一行,获得7,按顺序拼接成最终结果。
- 输入描述:
- 第一行是每次读取的固定长度,长度>0;
- 第2-n行是需要合并的数组,不同的数组用回车换行分隔,数组内部用逗号分隔。
- 输出描述:
- 输出一个新的数组,用逗号分隔。
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
ArrayList<String> list = new ArrayList<>();
while (!scanner.hasNext("#")){
list.add(scanner.next());
}
new Main().answer(num, list);
}
public void answer(int num, ArrayList<String> arrayList){
Map<Integer, Queue<Integer>> map = new HashMap<>(arrayList.size());
int count = 1;
for (String str : arrayList){
String[] split = str.split(",");
Queue<Integer> queue = new ArrayDeque<>();
for (String s : split) {
queue.add(Integer.valueOf(s));
}
map.put(count++, queue);
}
List<Integer> list = new ArrayList<>();
int key = 1;
while (!map.isEmpty()){
if (map.containsKey(key)) {
for (int i = num; i > 0; i--) {
if (map.get(key).isEmpty()){
map.remove(key);
break;
}
list.add(map.get(key).poll());
}
}
key++;
if (key > arrayList.size()){
key %= arrayList.size();
}
}
System.out.println(Arrays.toString(list.toArray()));
}
}