有两个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))
更好的查找所需元素的方法?
最佳答案
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
成本 = O(min(m, n))
关于algorithm - 如何在两个链表中找到最新的相等元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28812153/