(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;
        }
    }
原文地址:https://www.cnblogs.com/fdyang/p/4958765.html