求两个数组的交集

最好的办法是用hashtable, 时间复杂度最坏a.lengh+b.lengh

最差的用两个for. 时间复杂度 a*b

//求两个数组的交集
 给你两个排序的数组,求两个数组的交集。
//比如: A = 1 3 4 5 7, B = 2 3 5 8 9, 那么交集就是 3 5.
/*本文方法:
因为数组A B均排过序,所以,我们可以用两个“指针”分别指向两个数组的头部
如果其中一个比另一个小,移动小的那个数组的指针;
如果相等,那么那个值是在交集里,保存该值,这时,同时移动两个数组的指针。
一直这样操作下去,直到有一个指针已经超过数组范围。*/

namespace Example01
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] num1 = { 2, 3, 3, 4, 5 };
            int[] num2 = { 2, 2, 4, 5 };

            List<int> result = Intersection(num1, num2);
            string str1 = "abbcdef";
            string str2 = "bcdde";
            CompareHashTable(str1, str2);
        }

        static List<char> CompareHashTable(string a, string b)
        {
            Hashtable ht = new Hashtable();
            List<char> list = new List<char>();
            foreach (char ia in a)
            {
                if (!ht.Contains(ia))
                {
                    ht.Add(ia, ia);
                }
            }

            foreach (char ib in b)
            {
                if (ht.Contains(ib))
                {
                    if (!list.Contains(ib))
                    {
                        list.Add(ib);
                    }
                }
            }

            return list;
        }

        public static List<int> Intersection(int[] A, int[] B)
        {
            if (A == null || B == null || A.Length == 0 || B.Length == 0)
                return null;
            List<int> list = new List<int>();
            int i = 0;
            int j = 0;
            while (i < A.Length && j < B.Length)
            {
                if (A[i] < B[j])
                    i++;
                else if (A[i] > B[j])
                    j++;
                else
                {
                    list.Add(A[i]);
                    i++;
                    j++;
                }
            }

            return list;
        }
    }
}
View Code

 

转载于:https://www.cnblogs.com/binyao/archive/2013/05/02/3054840.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值