如何在多个列表中查找公共元素?
我有一个列表列表(嵌套列表)。 我需要找到它们之间的共同元素。
Example would be [1,3,5], [1,6,7,9,3], [1,3,10,11]
应该导致[1,3]
如果没有使用HashSet的retainAll方法,如何迭代所有要查找的元素?
谢谢,
你可以做什么:
Set intersection = new HashSet<>(lists.get(0)) for(List list : lists) { Set newIntersection = new HashSet<>(); for(Integer i : list) { if(intersection.contains(i)) { newIntersections.add(i); } } intersection = newIntersection; }
对单个列表进行排序会产生以下结果,对于排序,您可以对O(n(log(n)))复杂度使用任何合并排序
list1 --> [1,3,5] list2 --> [1,3,6,7,9] list3 --> [1,3,10,11]
一旦排序,使用具有最少元素数量的列表的外部循环,并在list2和list3中搜索。
例如
从list1中选择2项进行搜索,
在list2中搜索最多,找到列表排气或匹配元素,如果找到元素,则在list3中搜索其他明智的选择list1中的3项即5搜索。