Assume that set a has n elements, Set B has m elements, and the two sets are taken from a certain space (universe ).
1.1. First, start with the most naive method. For elements in B, perform a one-on-one test to determine whether the intersection and union are O (M * n) and square-level algorithms.
1.2. Sort a first, O (N * logn), and then test whether the elements in B are in A. In this case, we can divide them into two parts. O (M * logn ), A total of O (N * logn) + O (M * logn) = O (m + n) * logn ).
So if m <n, it is better to call A and B, that is, the complexity is O (m + n) * log (min (m, n ))).
The essence of this idea is to only use the fact that "A is a set" and then test the element is in a in B. the test process requires O (M * logn) complexity.
1.3, A and B are sorted, and the rest of the work is very similar to merge-sort. The two pointers go forward alternately. In the worst case, max (m, n) comparisons are required.
Maybe the sorting-based approach can be further optimized?
2.1. Now that the order has been completed, we will immediately know the range of the elements on both sides, for example, a in [a1, a2], B in [B1, B2], based on this upper and lower bounds, you can remove a part and then perform merge on the part that actually has an overlap. In extreme cases, most or even all elements can be removed based on the upper and lower bounds.
Another idea is to use hash-table.
3.1, A constructs a hash-table, O (n) insert. Then, test whether the elements in B are in the table. This time, even the second point is not used. The test of O (m) is O (m + n ).
What's the cost? Additional hash-table and O (n) tables (usually larger according to the hash-Table nature ).
Other ideas may apply to certain scenarios.
4.1. If the element range is small, you can use Bitmap (which is essentially a hash-table). The two sets are represented by two bitmaps. The intersection is and, and the Union is or, which is too convenient.
4.2. Another possible solution is Bloom filter. Open another blog, see: http://www.cnblogs.com/qsort/archive/2011/05/06/2039223.html