You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用嵌套foreach循环找出两个数组中的重复值?

问题

我需要找出两个不同数组中的重复值,希望避免代码冗余,用更简洁的方式实现。当前我用了嵌套两层foreach循环的方法,代码如下,请问有没有无嵌套foreach循环的简洁实现?

static void Main(string[] args)
{
    //Arrays to find the repeated values in both arrays
    int[] array1 = new int[5] { 1, 2, 3, 4, 5 };
    int[] array2 = new int[8] { 3, 5, 5, 9, 11, 13, 15, 17 };

    //Final Array
    int[] array3 = findTheIntersect(array1, array2);

    foreach (int item in array3)
    {
        Console.WriteLine($"{item}, Array Length: {array3.Length}");
    }
    Console.ReadKey();

}

public static int[] findTheIntersect(int[] arr1, int[] arr2)
{
    //Size of the final array
    int arrSize = 0;
    //Item variable that we will add to final array
    int arrItem = 0;
    //Temporary List to store repeated items
    List<int> arrList = new List<int>();

    foreach (int number in arr1)
    {
        int x = number;

        foreach (int number1 in arr2)
        {
            int y = number1;

            if (y == x && !arrList.Contains(number1))
            {
                arrSize++;
                arrItem = number1;
                arrList.Add(arrItem);
            }

        }
    }

    int[] finalArr = new int[arrSize];
    finalArr = arrList.ToArray();

    return finalArr;
}

我搜索现有解决方案时,只找到针对单数组重复值的处理方案,而非双数组对比的方案。


解决方案

方法1:使用LINQ的Intersect方法

这是最简洁的实现方式,.NET内置的LINQIntersect方法会直接返回两个序列的交集(自动去重),完全不需要手动编写循环:

using System.Linq; // 需引用此命名空间

public static int[] findTheIntersect(int[] arr1, int[] arr2)
{
    return arr1.Intersect(arr2).ToArray();
}

该方法内部已优化查找逻辑,时间复杂度远低于嵌套循环,同时代码极度简洁,完全符合你的需求。

方法2:使用HashSet手动实现

如果不想依赖LINQ,可以用HashSet来避免嵌套循环,利用哈希表O(1)的查找特性提升效率:

public static int[] findTheIntersect(int[] arr1, int[] arr2)
{
    HashSet<int> arr1Set = new HashSet<int>(arr1);
    HashSet<int> resultSet = new HashSet<int>();
    
    foreach (int num in arr2)
    {
        if (arr1Set.Contains(num))
        {
            resultSet.Add(num);
        }
    }
    
    return resultSet.ToArray();
}

这种方法仅需两次单循环,无嵌套逻辑,时间复杂度为O(n+m)(n、m分别为两个数组的长度),比原嵌套循环的O(n*m)效率提升明显,代码也足够简洁。


内容的提问来源于stack exchange,提问作者Can-Kar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:25:48