华为笔试题 -- 多个数组按顺序合并(Java代码实现)

题目描述:
现在有多组整数数组,需要将他们合并成一个新的数组。合并规则,从每个数组里按顺序取出固定长度的内容合并到新的数组中,取完的内容会删除掉,如果该行不足固定长度或者已经为空,则直接取出剩余部分的内容放到新的数组中,继续下一行。如样例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;
    }

输出结果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值