如果一个列表比另一个列表长,如何以递增顺序合并两个有序的ArrayList?

时间:2013-12-09 02:22:51

标签: java arraylist

我有一个家庭作业问题,我目前正在学习我的决赛。这是一个问题:

Write a static method named mergeSortedLists that takes two ArrayLists of Integers 
that are in increasing order and returns a new ArrayList of Integers that contains the
elements of the original lists "merged" together in increasing order.  For example, if the
first list contains the elements [1, 4, 4, 7, 22] and the second list is 
[3, 3, 5, 5, 21, 25, 30] then the new list should be 
[1, 3, 3, 4, 4, 5, 5, 7, 21, 22, 25, 30].  
Again, if one list is longer than the other append the remaining elements to the end of
the new list.

此问题的代码仅适用于给定的确切数字,并且仅当列表2长于列表1.如果列表1更长,我无法弄清楚如何使其工作。

这是我的代码:

private static ArrayList<Integer> mergeLists(ArrayList<Integer> list1, ArrayList<Integer> list2){
    ArrayList<Integer> out = new ArrayList<Integer>();
    int count1 = 0;
    int count2 = 0;
    if (list1.size() < list2.size())
    {
        while(count2 < list1.size()) 
        {
            if (count2 < list1.size() && list1.get(count1) < list2.get(count2))
            {
                out.add(list1.get(count1));
                count1++;
            }
            else if (count2 < list1.size() && list1.get(count1) > list2.get(count2))
            {
                out.add(list2.get(count2));
                count2++;
            }
        }
    }
    while (count1 < list1.size() || count2 < list2.size())
    {
        if (count1 < list1.size())
        {
            out.add(list1.get(count1));
            count1++;
        }
        else if (count2 <= list2.size())
        {
            out.add(list2.get(count2));
            count2++;
        }
    }
    return out;
}

2 个答案:

答案 0 :(得分:1)

您可以使用List的方法addAll()。 List Docs

注意ArrayList也有addAll()方法。

List<Integer> all = new ArrayList<Integer>();
all.addAll(list1);
all.addAll(list2);

Collections.sort(all);

答案 1 :(得分:0)

我会采用不同的方式

static List<Integer> mergeLists(List<Integer> list1, List<Integer> list2) {
    List<Integer> out = new ArrayList<Integer>();
    Iterator<Integer> i1 = list1.iterator();
    Iterator<Integer> i2 = list2.iterator();
    Integer e1 = i1.hasNext() ? i1.next() : null;
    Integer e2 = i2.hasNext() ? i2.next() : null;
    while (e1 != null || e2 != null) {
        if (e2 == null || e1 != null && e1 < e2) {
            out.add(e1);
            e1 = i1.hasNext() ? i1.next() : null;
        } else {
            out.add(e2);
            e2 = i2.hasNext() ? i2.next() : null;
        }
    }
    return out;
}