算法每一题,成长每一天~
C0E39 数组拼接
真题链接:【持续更新】2024华为 OD 机试E卷 机考真题库清单(全真题库)
思路
1、使用List<Queue>收集每个数组元素,,按索引循环遍历list, 取出对应queue中的 前k个元素,直到取空。
Java
package com.ccr.paper_f;
import java.util.*;
public class C0E39 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int k = in.nextInt();
int n = in.nextInt();
String no = in.nextLine(); // 跳过,到下一行
List<Queue<Integer>> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
Queue<Integer> queue = new LinkedList<>();
String[] split = in.nextLine().split(",");
for (String s : split) {
queue.add(Integer.parseInt(s));
}
list.add(queue);
}
int qIdx = 0;
List<String> result = new ArrayList<>();
int count = list.size();
while (count > 0) { // 直到所有队列都拿空
Queue<Integer> queue = list.get(qIdx);
for (int i = 0; i < k; i++) { // 每次拿k个
if (queue.isEmpty()) {
count--;
break;
}
result.add(String.valueOf(queue.poll()));
}
qIdx = ++qIdx % list.size();
}
System.out.println(String.join(",", result));
}
}
总结
~
算法要多练多练多练!!