基本上在面試的時候,會具體到兩個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; } }