zoukankan      html  css  js  c++  java
  • (C#) 求两个数组的交集

    基本上在面试的时候,会具体到两个int数组,或string数组。具体也就是讨论算法。

    首先需要的是和面试的人确认题目的含义,并非直接答题。

    然后,可以提出自己的想法,首先最快的是用linq

            {
                List<int> array0 = new List<int>() { 1, 2, 9, 3, 5, 2 };
                List<int> array1 = new List<int>() { 3, 2, 7 };
    
                List<int> arrayInterSect = array0.Intersect(array1).ToList(); // 交集

    最好写个函数:

            public List<int> GetInterSect(List<int> array0, List<int> array1)
            {
                return array0.Intersect(array1).ToList();
            }

    如果是差集合并集的话,可以用如下方法解决:

                List<int> arrayExcept = array0.Except(array1).ToList();  // 差集
                List<int> arrayUnion = array0.Union(array1).ToList();    // 并集


    当然,考算法的话,还需要进一步进行。

    基本思路可以口头说明是用两个for 循环,逐个匹配。 T(n) = O(n^2); 不要实现,因为O(n^2)的算法不好。

    其次稍好的方法可以先快排数组,然后两边同时开始遍历数组。时间复杂度是 O(nlogn).

    O(n)的算法才是期望的答案。可以采用Hashtable, 或者Dictionary.

            // The values in array0/array1 must be unique.
            public static List<int> GetIntersect(List<int> array0, List<int> array1)
            {
                Dictionary<int, int> dicIntersect = new Dictionary<int, int>();
                List<int> intersectData = new List<int>();
    
                // Traverse the first array.
                foreach (var data in array0)
                {
                    if (!dicIntersect.Keys.Contains(data))
                    {
                        dicIntersect.Add(data, 0);
                    }
    
                    dicIntersect[data]++;
                }
    
                // Traverse the second array.
                foreach (var data in array1)
                {
                    if (!dicIntersect.Keys.Contains(data))
                    {
                        dicIntersect.Add(data, 0);
                    }
    
                    dicIntersect[data]++;
                }
    
                // Traverse the dictionary to find the duplicated values.
                foreach (var intData in dicIntersect)
                {
                    if (intData.Value > 1)
                    {
                        intersectData.Add(intData.Key);
                    }
                }
    
                return intersectData;
            }
        }
  • 相关阅读:
    Java基础算法--排序
    Java基础之String类的细节问题
    Java数据结构四之——二叉树的前、中、后序遍历
    动态规划之----最长公共子序列(LCS)
    最长公共子串问题
    makefile学习笔记
    使用正则表达式,去除C++的注释
    gbk字库音序对照表
    Fsharp 类中的空字段
    使用FSharp 探索Dotnet图像处理功能2--均衡灰度
  • 原文地址:https://www.cnblogs.com/fdyang/p/4958765.html
Copyright © 2011-2022 走看看