问题
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