合并和订购列表

时间:2014-05-30 10:13:39

标签: java collections arraylist

对于任何两个升序排序的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;
  }
}

根据建议,有效的解决方案需要排序,其中位置是第一标准,是否是评论是第二标准。

2 个答案:

答案 0 :(得分:4)

这个答案不包含代码,你必须自己解决。

  1. 使用List
  2. addAll添加到另一个。{/ 1>
  3. 使用List
  4. 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运算符