Given a set of n pairs of integers, is there a fast way to determine if there exists two pairs (x1, y1) and (x2, y2) so that the intersection of the sets {x1, y1} and {x2, x2} is empty?
例如,{(0,1), (0,2), (2,1), (3,2)} 的答案为 {(0,1), (3,2)}。然而{(0,1),(0,2),(2,1)}没有这样的对。
在 Python 中,您可以按如下方式尝试所有对。
l = [(0,1), (0,2), (2,1), (3,2)]
print [pairs for pairs in itertools.combinations(l, 2)
if not (set(pairs[0]) & set(pairs[1]))]
This approach takes O(n2) time. Can you get something closer to linear time?