How to find common elements in multiple lists?

喜你入骨 提交于 2019-12-06 07:39:14

问题


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]

If not using the retainAll method of HashSet, how to iterate all the element to find?

Thanks,


回答1:


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;
}



回答2:


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

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.
for eg
pick 2 item from list1 to search,
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 i.e 5 to search.



来源:https://stackoverflow.com/questions/36110185/how-to-find-common-elements-in-multiple-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!