作业:寻找更好的策略或方法而不是完整的代码。
在两种情况下,我有两个整数数组列表:
- 第一个列表大于第二个
- 第二个列表大于第一个
我的目标是在两种情况下将 list2 的元素交错到 list1 中。我已经创建了一个方法来做到这一点,但我觉得我可以做得更好。
这是条件 1 的预期结果。请注意,在 list2 的元素用尽后,我们将 list1 的元素留在原处:
list1: [10, 20, 30, 40, 50, 60, 70]
list2: [4, 5, 6, 7]
Combined: [10, 4, 20, 5, 30, 6, 40, 7, 50, 60, 70]
这是条件 2 的预期结果。由于 list2 有更多元素,我们在 list1 用完后将这些元素附加到 list1:
list1: [10, 20, 30, 40]
list2: [4, 5, 6, 7, 8, 9, 10, 11]
Combined: [10, 4, 20, 5, 30, 6, 40, 7, 8, 9, 10, 11]
我的代码使用 if-else 语句来处理这两个条件。然后我使用迭代器遍历 list2 的元素并将它们插入到 list1 中。
public static void main(String[] Args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
//numbers.add(50);
//numbers.add(60);
//numbers.add(70);
ArrayList<Integer> numbers2 = new ArrayList<Integer>();
numbers2.add(4);
numbers2.add(5);
numbers2.add(6);
numbers2.add(7);
numbers2.add(8);
numbers2.add(9);
numbers2.add(10);
numbers2.add(11);
System.out.println("list1: " + numbers);
System.out.println("list2: " + numbers2);
interleave(numbers, numbers2);
System.out.println();
System.out.println("Combined: " + numbers);
}
public static void interleave(ArrayList<Integer> list1, ArrayList<Integer> list2)
{
//obtain an iterator for the collection
Iterator<Integer> itr2 = list2.iterator();
//loop counter
int count = 1;
//handle based on initial size of lists
if(list1.size() >= list2.size())
{
//loop through the first array and add elements from list 2 after each element
while(itr2.hasNext())
{
//insert elements from list2
list1.add(count, itr2.next());
//make sure elements are getting added at 1, 3, 5, 7, 9, etc
count = count + 2;
}
}
else if(list1.size() < list2.size())
{
//loop through the first array and add elements from list 2 after each element
while(itr2.hasNext())
{
if(count <= list1.size())
{
//insert elements from list2
list1.add(count, itr2.next());
//make sure elements are getting added at 1, 3, 5, 7, 9, etc
count = count + 2;
}
else
{
//fill in the remainder of the elements from list2 to list1
list1.add(itr2.next());
}
}
}
}