# 湖边的白杨树

:: :: :: :: :: :: :: ::
 213 随笔 :: 1 文章 :: 11 评论 :: 0 引用

        {
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();    // 并集

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[data]++;
}

// Traverse the second array.
foreach (var data in array1)
{
if (!dicIntersect.Keys.Contains(data))
{
}

dicIntersect[data]++;
}

// Traverse the dictionary to find the duplicated values.
foreach (var intData in dicIntersect)
{
if (intData.Value > 1)
{
}