Unity比较两个List中所含元素是否完全一致

5 篇文章 0 订阅

最近需要实现一个比较两个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中元素内容一致。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值