zoukankan      html  css  js  c++  java
  • 求两个数组的交集

    最好的办法是用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
  • 相关阅读:
    C#计算代码的执行耗时
    c#值类型和引用类型
    C#类、接口、虚方法和抽象方法
    15,了解如何在闭包里使用外围作用域中的变量
    函数闭包,golbal,nonlocal
    init())函数和main()函数
    函数的命名空间
    函数的默认参数是可变不可变引起的奇怪返回值
    遍历目录
    super顺序
  • 原文地址:https://www.cnblogs.com/binyao/p/3054840.html
Copyright © 2011-2022 走看看