我正在使用以下代码合并两个ArrayList
。代码工作并给了我想要的结果,但我想要一个更高效的版本。这里是条件。提高合并两个ArrayList的性能
- 方法接受两个列表,并且两个列表具有以递减顺序(5,4,3,2)
- 方法接受一个整数来决定所得
ArrayList
的大小的元件。 - 第一个输入列表大小永远不会超过生成的
ArrayList
的大小。
代码:
public ArrayList<Integer> mergeList(ArrayList<Integer> first,ArrayList<Integer> second, int n){
//case 1: when both list are null.
if(first == null && second == null)
return null;
//case 2: when first list is null but second list have elements
else if(first == null && second != null){
return second.size() >=n ? new ArrayList<Integer>(second.subList(0, n)) : second;
}
//case 3: when first list have record and second list is null
else if(first != null && second == null){
return first;
}
//case 4: when both list have elements
else {
first.addAll(second);
Collections.sort(first);
Collections.reverse(first);
return first.size()>=n ? new ArrayList<Integer>(first.subList(0, n)) : first;
}
}
}
这是不必要的复杂。 'ArrayList'根据需要扩展,所以不需要预先分配它(不需要参数'int n')。您应该只在开始时分配一次结果列表。我认为这里的目标是写一个适当的合并。连接列表和排序并不是最好的解决方案。如果由于某种原因,您仍然希望这样做,请按降序排序,以便您不必倒转列表。 –
@JimGarrison参数n是需求的一部分,所以我无法避免它,但我接受了您的建议并更新了我的代码。最新的代码被上传。 – Ashish
生成的列表是否也需要按相反顺序排列?在输入或结果中是否允许重复? – Bohemian