(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;
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM