简体   繁体   English

如何在多个列表中找到公共元素?

[英]How to find common elements in multiple lists?

I have a list of list (nest list).我有一个列表列表(嵌套列表)。 I need to find the common elements between those.我需要找到它们之间的共同点。

Example would be 
[1,3,5],
[1,6,7,9,3],
[1,3,10,11]

should result in [1,3]应该导致 [1,3]

If not using the retainAll method of HashSet, how to iterate all the element to find?如果不使用HashSet的retainAll方法,如何遍历所有元素进行查找?

Thanks,谢谢,

What you can do: 你可以做什么:

Set<Integer> intersection = new HashSet<>(lists.get(0))
for(List<Integer> list : lists) {
    Set<Integer> newIntersection = new HashSet<>();
    for(Integer i : list) {
        if(intersection.contains(i)) {
            newIntersections.add(i);
        }
    }
    intersection = newIntersection;
}

Do the sorting on individual list which will result in following result,for Sorting you can use any merge sort for O(n(log (n))) complexity 对单个列表进行排序会导致以下结果,对于排序,您可以对O(n(log(n))复杂度使用任何合并排序

list1 --> [1,3,5]
list2 --> [1,3,6,7,9]
list3 --> [1,3,10,11]

Once sorted use the outer loop for the list having minimum number of elements,and search in list2 and list3. 一旦排序,使用具有最少元素数量的列表的外部循环,并在list2和list3中搜索。
for eg 例如
pick 2 item from list1 to search, 从list1中选择2项进行搜索,
search in list2 up to , either the list exhausts or matching element is found , if element is found search in list3 other wise pick the 3 item from list1 ie 5 to search. 在list2中搜索最多,找到列表耗尽或匹配元素,如果找到元素,则在list3中搜索其他明智的选择list1中的3项即5搜索。

This code is written in Apex(similar to java)这段代码是用 Apex 编写的(类似于 java)

List<Integer> a = new List<Integer>{1,4,7,8};
List<Integer> b = new List<Integer>{2,5,3,6,4,8,9};
List<Integer> c = new List<Integer>{9,5,2,7,4};


for(integer i=0;i<a.size();i++){
    if(b.contains(a[i]) && c.contains(a[i])) {
        system.debug(a[i]);
    }
}

Output will be 4输出将为 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM