找到两组差异的最佳方法

时间:2012-03-11 22:16:14

标签: algorithm set compare

我有两组元素,我想要一个最佳算法来找到它们的差异或数学形式:A U B - A∩B

我认为的一种方式是

Bfound=0;
for (1->Na,i)
{
 flag=0;
 for (1->Nb,j)
 {
  if(A[i]==B[j])
  {
   flag=1;
   Bfound[j]=1;
  }

 }
 if (flag==0)
 print A[i]
}

for(1->Nb,i)
{
  if(Bfound[i]==0)
  print B[i]
}

这是最佳的吗?

2 个答案:

答案 0 :(得分:3)

回答你的问题 - 不,这不是最佳选择。您的解决方案的复杂性是O(nm)时间,其中n和m分别是A和B的大小。如果n~m,你可以把这个时间提高到O(nlogn + mlogm)。

  1. n log n + m log m时间内对两个数组进行排序。
  2. n+m时间内找到交叉点:

    i = 0; 
    j = 0;
    while(i < n && j < m) {
      if (A[i] == B[j]) {
        print(A[i]);
        i++;
        j++;
      } else if (A[i] < B[j]) {
        i++;
      } else {
        j++;
      } 
    }
    

答案 1 :(得分:1)

对称差异:A∪B - A∩B即,返回包含A或B中元素但不同时两者的新集合。从定义直接的方式:

# result = A ^ B
result = set() # start with empty set

# add all items that are in A but not in B
for item in A: # for each item in A; O(|A|), where |A| - number of elements in A
    if item not in B: # amortized O(1) (for hash-based implementation)
       result.add(item) # amortized O(1) (for hash-based implementation)

# add all items that are in B but not in A
for item in B:
    if item not in A:
       result.add(item)

复杂性O(|A|+|B|)

在C ++中,类型为unordered_set,在Java中,C# - HashSet,在Python中 - set

另一种方法(used in Python)是将A复制到结果中,然后尝试从结果中删除B项:

# result = A ^ B
result = set(A) # copy A into result
for item in B:
    try: result.remove(item) # O(1)
    except KeyError: # item was not in the result
        result.add(item) # add previously not-found item

复杂性O(|A|+|B|)