执行“包含”的有效方法两个列表之间
我有 2 个整数列表,
l1 = new ArrayList();
l2 = new ArrayList();
我想找出其中的重复项,我有我通常的方法:-
for (Integer i : l1)
{
if(l2.contains(i)){
System.out.println("Found!");
}
}
我听说 contains()
是 O(n)
code>,使我的实现O(n^2)
。
有没有更好的方法来做到这一点(小于O(n^2)
)?
I have 2 lists of integers,
l1 = new ArrayList();
l2 = new ArrayList();
I want to find out duplicate items in both of them, I have my usual approach:-
for (Integer i : l1)
{
if(l2.contains(i)){
System.out.println("Found!");
}
}
I've heard contains()
is O(n)
, making my implementation O(n^2)
.
Is there a better way to do this, (less than O(n^2)
) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然 - 首先从列表之一创建一个
HashSet
。如果您想查找所有重复的条目,您甚至不需要编写自己的循环,因为
Set
提供了您需要的一切...之后,
set
将是两个列表的交集。请注意,如果您的两个列表一开始就已经排序,那么您的效率可能会更高。您只需同时迭代两者,将“光标”向前移动到当前具有较小值的迭代器。
Sure - create a
HashSet<Integer>
from one of the lists first.If you want to find all duplicate entries, you don't even need to write your own loop, as
Set<E>
provides everything you need...Afterwards,
set
will be the intersection of the two lists.Note that you can be even more efficient than this if both your lists are already sorted to start with. You just iterate over both at the same time, moving the "cursor" forward for whichever iterator currently has the smaller value.
通常的方法是将第一个列表中的每个项目添加到 HashSet 中,然后测试第二个列表中的每个项目是否存在于该集合中:
The usual way is to add each item from the first list to a
HashSet
, and then test each item in the second list for existence in that set: