最好的办法是用hashtable, 时间复杂度最坏a.lengh+b.lengh
最差的用两个for. 时间复杂度 a*b
//求两个数组的交集
给你两个排序的数组,求两个数组的交集。
//比如: A = 1 3 4 5 7, B = 2 3 5 8 9, 那么交集就是 3 5.
/*本文方法:
因为数组A B均排过序,所以,我们可以用两个“指针”分别指向两个数组的头部
如果其中一个比另一个小,移动小的那个数组的指针;
如果相等,那么那个值是在交集里,保存该值,这时,同时移动两个数组的指针。
一直这样操作下去,直到有一个指针已经超过数组范围。*/
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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; } } }