最近需要实现一个比较两个List里边的元素是否一致的功能,它们的顺序可以不一致。复杂度为n2的办法有很多,在StackOverflow上找到了一个方法的复杂度为n,在这里记录一下
public static bool CompareLists<T>(List<T> aListA, List<T> aListB)
{
if (aListA == null || aListB == null || aListA.Count != aListB.Count)
return false;
if (aListA.Count == 0)
return true;
Dictionary<T, int> lookUp = new Dictionary<T, int>();
// create index for the first list
for(int i = 0; i < aListA.Count; i++)
{
int count = 0;
if (!lookUp.TryGetValue(aListA[i], out count))
{
lookUp.Add(aListA[i], 1);
continue;
}
lookUp[aListA[i]] = count + 1;
}
for (int i = 0; i < aListB.Count; i++)
{
int count = 0;
if (!lookUp.TryGetValue(aListB[i], out count))
{
// early exit as the current value in B doesn't exist in the lookUp (and not in ListA)
return false;
}
count--;
if (count <= 0)
lookUp.Remove(aListB[i]);
else
lookUp[aListB[i]] = count;
}
// if there are remaining elements in the lookUp, that means ListA contains elements that do not exist in ListB
return lookUp.Count == 0;
}
在这段程序中,首先遍历第一个list中的所有元素,并把元素保存在一个dictionary中,如果这个元素第一次出现,就记录value为1,否则按第几次出现记录value。
然后遍历第二个list中的所有元素,如果没有在字典中找到对应的元素,就返回false,否则返回元素在字典中的编号,并将编号减一,如果编号变为0,就将该元素从字典中移除,否则将字典中该元素的value更新。这个行为可以保证即使顺序不一致也可以保证数量一致,最后如果字典被完全清空,则两个list中元素内容一致。