【问题标题】:How to find latest equal element in two linked lists?如何在两个链表中找到最新的相等元素?
【发布时间】:2015-03-02 14:25:07
【问题描述】:

有两个linked lists。它们有共同的尾巴。我想找到两个列表中相同的最新元素。

例如,

List1 是 10->4->5->2->9->53->64->345->23

List2 是 10->4->5->2->8->53->64->345->23->43- >53

我想找到 2 个。

我们可以遍历O(n) 中的列表。

有没有比O(min(n, m))更好的方法来找到所需的元素?

【问题讨论】:

  • 遍历链表的唯一方法是 O(n),所以我看不出有比 O(n + m) 更好的算法。
  • O(n + m) 是一个显而易见的答案。我希望,有更好的解决方案...
  • 好吧,我想严格来说,最明显的算法的答案是 O(min(m, n))。
  • @Phylogenesis,是的,你是对的。我对时间的估计弄错了。

标签: algorithm search linked-list tail


【解决方案1】:
node1 = list1head
node2 = list2head
ans = {error}
while(node1 && node2 && node1.data == node2.data)
  ans = node1.data
  node1 = node1.next
  node2 = node2.next
end while
return ans

Cost = O(min(m, n))

【讨论】:

  • 感谢您的回答。这是一个正确的解决方案,但我希望,可能有一些东西,比这个算法更好。
  • 对于单链表,你不能比这更快地遍历。
猜你喜欢
  • 2014-04-09
  • 1970-01-01
  • 2013-06-26
  • 2015-01-05
  • 1970-01-01
  • 2016-12-28
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
相关资源
最近更新 更多