(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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值