2013-12-09 29 views
0

我有一個家庭作業問題,而我目前正在用於研究我的決賽。這裏的問題是:如果一個列表比另一個列表更長,如何合併兩個有序的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; 
} 
+0

您可以用'中的addAll()'和'Collections.sort()'? –

回答

1

你可以用列表的方法中的addAll()。 List Docs

注意ArrayList也有方法addAll()。

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

Collections.sort(all); 
+0

我沒有使用這種方法,因爲我不確定教授是否會接受它。之前在HW上的問題給了我們2個不合適的列表,並且讓我們交織了列表。所以[1,5,2]和[3,1,7]合併爲[1,3,5,1,2,7]。看起來他希望我們對這個問題使用相同的方法,並且應該將更長列表中剩餘的任何內容添加到結果列表中。 – JSolo714

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; 
} 
相關問題