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

最近需要实现一个比较两个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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值