编写一个合并两个数组列表的方法,交替使用两个数组列表中的元素 [英] Write a method that merges two array lists, alternating elements from both array lists

查看:1246
本文介绍了编写一个合并两个数组列表的方法,交替使用两个数组列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写方法


public static ArrayList merge(ArrayList a,ArrayList b)

public static ArrayList merge(ArrayList a, ArrayList b)

合并两个数组列表,交替使用两个数组列表中的元素。如果一个数组列表比另一个更短,则只要可以替换,然后从较长的数组列表中追加剩余的elemts。例如,如果a是

that merges two array lists, alternating elements from both array lists. If one array list is shorter than the other, then alternate as long as you can and then append the remaining elemts from the longer array list. For example, if a is


1 4 9 16

1 4 9 16

和b是


9 7 4 9 11

9 7 4 9 11

然后合并返回数组列表


1 9 4 7 9 4 16 9 11

1 9 4 7 9 4 16 9 11






我尝试做的是用if语句编写for循环,以便在合并中添加一个数字数组列表中的数组列表a当i是偶数时(i%2 == 0),当i是奇数时,从数组列表b开始。然而,我不知道如何处理一个数组列表可能比另一个更长的事实。有人可以帮帮我吗?


What I tried doing was writing a for loop with if statements such that a number is added to the merge array list from array list a when i is an even number (i%2==0) and from array list b when i is an odd number. I am however not sure how to deal with the fact that one array list can be longer than the other. Could anyone please help me out?

编辑:好的,这是代码(但它远非正确):

EDIT: Ok, here is the code (but it is far from correct):

public static ArrayList<Integer> merge(ArrayList<Integer> een, ArrayList<Integer> twee)
{
    ArrayList<Integer> merged = new ArrayList<Integer>();

    for(int i = 0; i<100; i++)
    {           
        if(i%2!=0)
        {
            merged.add(a.get(i));
        }   
        if(i%2 == 0)
        {
            merged.add(b.get(i));
        }               
    }

    System.out.println(merged);
    return merged;
}


推荐答案

没有迭代器:

public static ArrayList merge(ArrayList a, ArrayList b) {
    int c1 = 0, c2 = 0;
    ArrayList<Integer> res = new ArrayList<Integer>();

    while(c1 < a.size() || c2 < b.size()) {
        if(c1 < a.size())
            res.add((Integer) a.get(c1++));
        if(c2 < b.size())
            res.add((Integer) b.get(c2++));
    }
    return res;
}

这篇关于编写一个合并两个数组列表的方法,交替使用两个数组列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆