隨着LINQ,這是微不足道的,因爲你可以調用Intersect
extension method上Enumerable
class給你兩個數組的交集:
var intersection = ListA.Intersect(ListB);
然而,這是設置路口,這意味着如果ListA
和ListB
沒有獨特的值,你不會得到任何副本。換句話說,如果你有以下:
var ListA = new [] { 0, 0, 1, 2, 3 };
var ListB = new [] { 0, 0, 0, 2 };
然後ListA.Intersect(ListB)
生產:
{ 0, 2 }
如果您期望:
{ 0, 0, 2 }
然後你將不得不保持當您掃描兩個列表時,您自己的項目數和收益/遞減項。
首先,你要收集單個項目的列出了Dictionary<TKey, int>
:
var countsOfA = ListA.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count());
從那裏,你可以掃描ListB
並放置在列表中,當你在countsOfA
遇到一個項目:
:
// The items that match.
IList<int> matched = new List<int>();
// Scan
foreach (int b in ListB)
{
// The count.
int count;
// If the item is found in a.
if (countsOfA.TryGetValue(b, out count))
{
// This is positive.
Debug.Assert(count > 0);
// Add the item to the list.
matched.Add(b);
// Decrement the count. If
// 0, remove.
if (--count == 0) countsOfA.Remove(b);
}
}
您可以在推遲執行,像這樣的擴展方法包裝這件事
注意,這兩種方法是(和我道歉,如果我在這裏屠宰大O符號)O(N + M)
其中N
是第一個數組中的項目數,並M
是項目的第二陣列中的數。您必須僅掃描一次每個列表,並且假定獲取哈希代碼並在哈希代碼上執行查找是O(1)
(常量)操作。
不是BinarySearch依靠被排序的列表嗎? http://msdn.microsoft.com/en-us/library/w4e7fxsh.aspx – 2009-01-07 06:45:21