Basically in the interview, will be specific to two int array, or string array. Specifically, the discussion algorithm.
The first thing you need is to confirm the meaning of the topic with the interviewer, not the direct answer.
Then, you can come up with your own ideas, first and foremost with LINQ
{List<int> array0 =Newlist<int> () {1,2,9,3,5,2 }; List<int> array1 =Newlist<int> () {3,2,7 }; List<int> arrayintersect = array0. Intersect (array1). ToList ();//intersection
It's best to write a function:
Public list<int> getintersect (list<int> array0, list<int> array1) { return array0. Intersect (array1). ToList (); }
If it is a difference set merge set, the following methods can be solved:
list<int> arrayexcept = array0. Except (array1). ToList (); // difference Set list<int> arrayunion = array0. Union (array1). ToList (); // and set
Of course, the algorithm will need to be further.
The basic idea can be verbally explained by using two for loops, matching one after the other. T (n) = O (n^2); Do not implement, because O (n^2) algorithm is not good.
Second, a slightly better way to first quickly array, and then both sides began to iterate over the array. The complexity of Time is O (NLOGN).
The O (n) algorithm is the desired answer. You can use Hashtable, or dictionary.
//The values in Array0/array1 must is unique. Public Staticlist<int> Getintersect (list<int> Array0, list<int>array1) {Dictionary<int,int> dicintersect =Newdictionary<int,int>(); List<int> intersectdata =Newlist<int>(); //Traverse the first array. foreach(varDataincharray0) { if(!dicIntersect.Keys.Contains (data)) {Dicintersect.add (data,0); } Dicintersect[data]++; } //Traverse the second array. foreach(varDataincharray1) { if(!dicIntersect.Keys.Contains (data)) {Dicintersect.add (data,0); } Dicintersect[data]++; } //Traverse the dictionary to find the duplicated values. foreach(varIntdatainchdicintersect) { if(Intdata.value >1) {intersectdata.add (Intdata.key); } } returnIntersectdata; } }
(C #) to find the intersection of two arrays