我有一個家庭作業問題,而我目前正在用於研究我的決賽。這裏的問題是:如果一個列表比另一個列表更長,如何合併兩個有序的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;
}
您可以用'中的addAll()'和'Collections.sort()'? –