最近需要实现一个比较两个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 fa