对于任何两个升序排序的ArrayList<Integer>
,例如
List<Integer> l1 = new ArrayList<Integer>();
l1.add(1);
l1.add(2);
l1.add(5);
l1.add(10);
和
List<Integer> l2 = new ArrayList<Integer>();
l2.add(1);
l2.add(3);
l2.add(5);
l2.add(11);
如何将它们合并到值为
的ArrayList<Integer>
中
1,1,2,3,5,5,10,11
更新
意识到Integer
过分简化了问题;实际上这些是类
public class Tuple {
public boolean isComment;
public int location;
public String text;
public Tuple(boolean isAComment, int aLocation, String aText) {
isComment = isAComment;
location = aLocation;
text = aText;
}
}
根据建议,有效的解决方案需要排序,其中位置是第一标准,是否是评论是第二标准。
答案 0 :(得分:4)
这个答案不包含代码,你必须自己解决。
List
addAll
添加到另一个。{/ 1>
List
Collections.sort
进行排序
醇>
答案 1 :(得分:2)
您是否正在实施merge-sort?
&#34; bycicle&#34; -way(O(n)
):
public List<Integer> merge (List<Integer> l1, List<Integer> l2) {
List<Integer> result = new ArrayList<>();
int i1 = 0, i2 = 0;
while (i1 < l1.size() && i2 < l2.size())
if (l1.get(i1) < l2.get(i2))
result.add (l1.get(i1++));
else
result.add (l2.get(i2++));
while (i1 < l1.size())
result.add (l1.get(i1++));
while (i2 < l2.size())
result.add (l2.get(i2++));
return result;
}
如果List<Tuples>
不会发生太大变化,只需制作Tuple
Comparable
:
public class Tuple implement Comparable <Tuple> {
public boolean isComment;
public int location;
public String text;
public Tuple(boolean isAComment, int aLocation, String aText) {
isComment = isAComment;
location = aLocation;
text = aText;
}
public int compareTo (Tuple that) {
if (location == that.location)
return Boolean.compare (isComment, that.isComment);
else
return Integer.compare (location, that.location);
}
}
然后,您应该使用<
l1.get(i1).compareTo(l2.get(i2)) < 0
运算符