Today I encountered a pen question: there are two arrays A and B, with the length of M and N respectively. Find the same element in the two arrays with the number of comparisons not greater than m + n. I didn't do it at the time. Now I am giving C #, which makes up a little regret.
Using system; using system. collections. generic; using system. LINQ; using system. text; namespace sortab {class program {static void main (string [] ARGs) {int [] A = randomintarray (10 ); // M = 10 int [] B = randomintarray (5); // n = 5 // outputs two arrays of console. write ("array A:"); foreach (INT m in a) console. write ("{0}", M. tostring (); console. write ("\ n Array B:"); foreach (int n in B) console. write ("{0}", N. tostring ()); // Find the same element in the array stringbuilder list = new stringbuilder (); foreach (INT m in a) {int getint = find (M, B); If (getint! =-1) list. append (B [getint]);} console. writeline (); console. write ("repeated elements in the two arrays include: {0}", list); // use the intersection of the two arrays to verify ienumerable <int> intersect =. intersect (B); console. write ("\ n intersection of two Arrays:"); foreach (INT vars in intersect) console. write ("{0}", vars); console. readline ();} // binary search. N must be an ordered array; otherwise, the public static int find (INT key, int [] n) {int lB = 0; int UB = n. length-1; int temp; while (true) {temp = (Lb + UB)/2; If (N [temp] = Key) return temp; else if (Lb> UB) Return-1; else {If (N [temp] <key) lB = temp + 1; else UB = temp-1 ;}}} public static int [] randomintarray (INT count) {int [] array = new int [count]; random r = new random (unchecked (INT) datetime. now. ticks); For (INT I = 0; I <count; I ++) {array [I] = R. next (100) ;}return array ;}}}
However, I am still confused: the number of comparisons may be greater than m + n.