Computing set intersection in linear time?
问题 Is there an algorithm that, given two sets, computes their intersection in linear time? I can run two for loops to check all pairs of elements, recording elements that I find in both of the sets. However, the runninng time will be O(n 2 ). How do I do this in O(n) time? 回答1: That depends on your set implementation. If you have a hash set (O(1) lookup), then the approach indicated by all the other posters is correct. Iterate across all the elements in the first set. If it's in the second set,