求集合的交集
给定两个数组,求两个数组的交集。
1 string[] a = new string[] { "khlin", "hzluo", "jjguo", "hhchen", "jxhan", "lxiao", "jsxiao", "wwang", "lsxie", "lwang" }; 2 string[] b = new string[] { "hzluo", "wcxu", "khlin", "shchen", "wzhang", "jxhan", "lxiao", "lwang" }; 3 4 5 foreach (string stra in a) 6 Console.Write("{0} ", stra); 7 Console.WriteLine(); 8 foreach (string strb in b) 9 Console.Write("{0} ", strb); 10 Console.WriteLine(); 11 IList<string> list = new List<string>(); 12 13 //方法一:两数组遍历,最简单粗暴的做法,时间复杂度为O(N^2) 14 foreach (string stra in a) 15 { 16 foreach (string strb in b) 17 { 18 if (stra == strb) 19 { 20 list.Add(stra); 21 break; 22 } 23 } 24 } 25 Console.WriteLine("方法一:"); 26 foreach (string str in list) 27 { 28 Console.Write("{0} ", str); 29 } 30 Console.WriteLine(); 31 32 //方法二:利用Hashset 33 list.Clear(); 34 HashSet<string> hashset = new HashSet<string>(); 35 foreach (string stra in a) 36 hashset.Add(stra); 37 foreach (string strb in b) 38 { 39 if (!hashset.Add(strb))//无法加入,说明a也存在,加入交集的集合 40 list.Add(strb); 41 } 42 Console.WriteLine("方法二:"); 43 foreach (string str in list) 44 { 45 Console.Write("{0} ", str); 46 } 47 Console.WriteLine(); 48 49 //方法三:排序,利用两个游标不断对比,找出相同的元素 50 QuickSort(a, 0, a.Length - 1); 51 QuickSort(b, 0, b.Length - 1);//排序 52 list.Clear(); 53 int i, j; 54 i = j = 0;//设置两游标 55 while (i <= a.Length - 1 && j <= b.Length - 1) 56 { 57 if (a[i].CompareTo(b[j]) > 0)//由于是从小到大排序,当前a游标大于b游标,b游标下移一位 58 j++; 59 else if (a[i].CompareTo(b[j]) < 0)//同上 60 i++; 61 else//找到相同的,加入交集集合,两游标同时下移一位,继续比较 62 { 63 list.Add(a[i]); 64 i++; 65 j++; 66 } 67 } 68 Console.WriteLine("方法三:"); 69 foreach (string str in list) 70 { 71 Console.Write("{0} ", str); 72 } 73 Console.WriteLine(); 74 Console.Read();