Comparing two arrays in C#

2020-03-01 02:08发布

bool hasDuplicate = false;   
int[] a = new int[] {1, 2, 3, 4};
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };

I need compare all elements of array A with element of array B and in case of a duplicate element in B, set hasDuplicate on TRUE.

标签: c# arrays
11条回答
走好不送
2楼-- · 2020-03-01 02:27

To efficiently compare all elements in one set to another, you can make a HashSet of one of them. Also, you can exit out of the loop as soon as you find the first match:

HashSet<int> h = new HashSet<int>(a);
foreach (int i in b) {
  if (h.Contains(i)) {
    hasDuplicate = true;
    break;
  }
}

This is an O(n+m) solution, compared to having two nested loops comparing all values which is an O(n*m) solution.

查看更多
三岁会撩人
3楼-- · 2020-03-01 02:28

You should sort your data, O(nlog n) and then you could simply do a one pass through each of them, O(n), where you increment the lowest of them. Be aware of data with same number twice, e.g:

a = {1 3 3 5 8}

b = {2 3 5 5 8}

查看更多
趁早两清
4楼-- · 2020-03-01 02:29

I did it with for loop. The point is that we compare each member to members from array b. So a[0] is compared to every member in the array b first and then it goes to a[1] and does the same thing, and so on, until it finds a match.

bool hasDuplicate = false;

int[] a = new int[] { 1, 2, 3, 4 };
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };

for (int i = 0; i < a.Length; i++)
{
    for (int j = 0; j < b.Length; j++)
    {
        if (a[i] == b[j])
        {
            hasDuplicate = true;
        }
    }
}
查看更多
冷血范
5楼-- · 2020-03-01 02:29

Why don't we try to use LINQ? Check out the following code,

public bool Checking()
    {
        bool hasDuplicate = false;
        int[] a = new int[] { 1, 2, 3, 4 };
        int[] b = new int[] { 5, 6, 1, 2, 7, 8 };

        int count = a.Intersect(b).Count();
        if (count >= 1)
            hasDuplicate = true;

        return hasDuplicate;

    }
查看更多
做个烂人
6楼-- · 2020-03-01 02:36

I know you don't want a one line solution but I'll leave my answer for other users who might want a simple solution for the same problem.

If you don't want to use Linq, you could use SequenceEqual.

bool equal = Array1.SequenceEqual(Array2);

Hope it helps.

查看更多
登录 后发表回答