如何在线性时间内找到两个有序链表中的公共元素?

时间:2015-09-15 18:22:45

标签: performance linked-list

让A和B成为两个有序链表。编写一个查找A和B的公共元素的方法(如果存在)。运行时间应该是线性的

我的解决方案:

public void search(SLLNode A, SLLNodeB){ for(int i=0;i<A.size();i++){ for(int j=0;j<B.size();j++){ if(a.head==b.head){ return a.head; } else{ a.head=a.next; b.head=b.next; } } } } 问题是我不确定这个解决方案是否有效。由于嵌套循环,我也不认为这是线性时间。

有没有更快的方式来写这个?提前致谢。我在一年多的时间里没有编写代码,所以我在语法上有点迷失。

1 个答案:

答案 0 :(得分:0)

这是该问题的一种可能的线性解决方案。

public static Integer common(List<Integer> l1, List<Integer> l2) {
    int j = 0;
    int k = 0;
    while ( j < l1.size() && k < l2.size() ) {
        if (l1.get(j).intValue() == l2.get(k).intValue()) return l1.get(j);
        else if (l1.get(j).intValue() > l2.get(k).intValue()) k++;
        else j++;
    }
    return null;
}

测试场景:

public static void main(String[] args) {
    List<Integer> l1 = new LinkedList();
    List<Integer> l2 = new LinkedList();
    for (int i=0; i<10; i++) l1.add(i);
    for (int i=10; i<20; i++) l2.add(i);
    l1.add(15);
    System.out.println(common(l1,l2));
}   

<强>方法 让我们说列表是l1和l2。元素表示为e1,e2 ......等

您逐个查看列表中的每个元素并检查:

  • 如果l1中的e1 = l1中的= e1,则返回e1
  • 如果l1中的e1> l2中的e1然后在l2
  • 中向前移动一个元素
  • 如果l1中的e1 < l2中的e1然后在l1
  • 中向前移动一个元素

继续重复上述步骤,直到其中一个列表到达结尾或其中一个元素相等。