How to find common elements in multiple lists?

让人想犯罪 __ 提交于 2019-12-04 12:05:57

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

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.

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