Hello
Thank you everyone for your excellent analysis of algorithm based on the big O.
Ibtesam, if you want a simple coding version, please refer to this sample code:
using System.Linq;
int[] elementSet1 = { 5, 1, 6, 3, 8 };
int[] elementSet2 = { 3, 7, 8, 6, 5 };
foreach (int element in elementSet1.Intersect(elementSet2))
{ Console.WriteLine(element); }
Inside the Intersect extension method, it does something like this:
public static IEnumerable<T> Intersect<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
Dictionary<T, object> dict = new Dictionary<T, object>();
foreach (T element in first) dict[element] = null;
foreach (T element in second)
{
if (dict.ContainsKey(element)) dict[element] = dict;
}
foreach (KeyValuePair<T, object> pair in dict)
{ if (pair.Value != null) yield return pair.Key; }
}
Regards,
Jialiang Ge
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.