简体   繁体   English

如何比较两个未排序的int数组中的值?

[英]how can i compare values in two unsorted int arrays?

I need to find the same values (if there is) in both int arrays. 我需要在两个int数组中找到相同的值(如果有)。 I think it would work with Binary Search but i don't know exacly how to do it. 我认为它可以与Binary Search一起使用,但我不知道该怎么做。 eg: 例如:

    g1[95 78 99 95 35 65 95]
    g2[67 100 95 76 95 99 60]

    the function returns 2 (for 95 and 99).

You could use Enumerable.Intersect : 您可以使用Enumerable.Intersect

int[] duplicates = g1.Intersect(g2).ToArray();

If you just want to know the number of duplicates: 如果您只想知道重复的数量:

int duplicates = g1.Intersect(g2).Count();

You can use LINQ Intersect 您可以使用LINQ Intersect

        var g1 = new[] { 95, 78, 99, 95, 35, 65, 95 };
        var g2 = new[] { 67, 100, 95, 76, 95, 99, 60 };
        var result = g1.Intersect(g2).Count();
Var duplicates = g1.Intersect(g2).Count();

希望能帮助到你。

Try this 尝试这个

            int[] g1 = { 95, 78, 99, 95, 35, 65, 95 };
            int[] g2 = { 67, 100, 95, 76, 95, 99, 60 };

            int[] results = g1.Where(x => g2.Contains(x)).Distinct().ToArray();

A nested for each should do: 每个嵌套都应执行以下操作:

void a(int[] g1, int[] g2)
{
    int counter = 0;
    foreach (var x in g1)
    {
        foreach (var y in g2)
        {
            if (y == x) counter++;
        }
    }
}

Try this 尝试这个

int compare(int g1[], int g2[])
{
    int count = 0;
    for(int i=0; i < g1.length; i++)
    {
        for(int j=0; j < g2.length; j++)
        {
          if(g1[i] == g2[j])
            count = count + 1;
        }
    }
    return count;
}

This code compare each array element of g1 with all of the second(g2), if he find a element equal increments the counter. 此代码将g1的每个数组元素与所有second(g2)进行比较,如果他发现相等的元素将使计数器递增。 The code is a little big, but I think it's easier for you to understand how it works 代码有点大,但是我认为您更容易理解它的工作原理

使用相交var r = g1.Intersect(g2)并使用foreach循环从r获取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM