Better way to find matches in two sorted lists than using for loops?(在两个排序列表中查找匹配项比使用 for 循环更好的方法?)
问题描述
我有两个排序列表,都是非递减顺序.例如,我有一个带有元素 [2,3,4,5,6,7...]
的排序链表,另一个带有元素 [5,6,7,8,9...]
.
I have two sorted lists, both in non-decreasing order. For example, I have one sorted linked list with elements [2,3,4,5,6,7...]
and the other one with elements [5,6,7,8,9...]
.
我需要在两个列表中找到所有共同的元素.我知道我可以使用 for 循环和嵌套循环来迭代所有匹配项以找到相同的两个元素.但是,是否有另一种运行时间小于 O(n^2)
的方法?
I need to find all common elements in both lists. I know I can use a for loop and a nested loop to iterate all matches to find the same two elements. However, is there another way to do this that has running time less than O(n^2)
?
推荐答案
你可以在 O(n) 时间内完成.伪代码:
You can do it in O(n) time. Pseudocode:
a = list1.first
b = list2.first
repeat:
if a == b:
output a
a = list1.next
b = list2.next
elif a < b:
a = list1.next
else
b = list2.next
until either list has no more elements
这篇关于在两个排序列表中查找匹配项比使用 for 循环更好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在两个排序列表中查找匹配项比使用 for 循环更好的方法?


- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01