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

Source: Internet
Author: User
Tags vars

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.