检查两个集合在C#中是否不相交的最快方法是什么? [英] What is the fastest way to check if two sets are disjoint in C#?

查看:45
本文介绍了检查两个集合在C#中是否不相交的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到了很多关于如何检查是否有两个数组不相交的问题,包括使用Enumerable.Intersect和Enumerable.Distinct调用,但是我想知道是否有更快的方法来做我需要的事情。我只需要检查两个数组是否包含任何公共元素。我有三百万个阵列需要互相检查,所以我需要拨打很多电话,并且想知道是否有更快的方法来执行以下功能:



I found a lot of answers online on how to check if two arrays are disjoint that involved the use of Enumerable.Intersect and Enumerable.Distinct calls, however I was wondering if there was a faster way to do what I need. I merely need to check if two arrays do not contain any common elements. I have three million arrays that I need to check with each other so I need to make a lot of calls and was wondering if there was any faster way to perform the following function:

private static bool checkIfDisjoint(int[] a, int[] b)
{
      for(int i = 0; i < a.Length; i++)
      {
            for (int j = 0; j < b.Length; j++)
            {
                   if (a[i] == b[j])
                         return false;
            }
      }
      return true;
}





我需要拨打很多电话,每个阵列的长度都小于4所以我想知道是否有更快的方法来实现这个目标。



我尝试过的事情:



我已经尝试过LINQ和上面的代码块,并且想知道我的数组的长度是否永远不超过4,并且我只有180个不同的字符,数组可以包含,我可以做些什么来使这个操作更快。



I need to make a lot of calls and each of my arrays are less than length 4. So I was wondering if there was a faster way to achieve this.

What I have tried:

I've tried LINQ and the code block above, and was wondering if given the fact that the length of my arrays are never more than 4, and I have only 180 different characters which the arrays can contain, there was something I could do to make this operation faster.

推荐答案

你好,



As在PIEBALDconsult上面的评论中提到你可以使用HashSet。

我建议使用Overlaps()方法返回一个布尔值,表示存在相同的元素。



Hello,

As mentioned in the comment above by PIEBALDconsult you can use a HashSet.
What I would suggest is using the Overlaps() method that will return a boolean indicating the presence of identical elements.

HashSet<int> set = new HashSet<int>(array1);
bool a = set.Overlaps(array2);





谢谢。



Thanks.


这篇关于检查两个集合在C#中是否不相交的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆