Given two sorted arrays, how can we efficiently determine whether the two arrays contain the same number?

Source: Internet
Author: User

The first question comes to mind is an O (nlogn) algorithm. An array is randomly selected to traverse all elements of the array. During the traversal process, binary search is performed on each element in the first array in the other array. Use C ++ to implement the Code as follows:

 

  1. Bool findcommon (int A [], int size1, int B [], int size2)
  2. {
  3. Int I;
  4. For (I = 0; I <size1; I ++)
  5. {
  6. Int start = 0, end = size2-1, mid;
  7. While (start <= end)
  8. {
  9. Mid = (start + end)/2;
  10. If (A [I] = B [Mid])
  11. Return true;
  12. Else if (a [I] <B [Mid])
  13. End = mid-1;
  14. Else
  15. Start = Mid + 1;
  16. }
  17. }
  18. Return false;
  19. }

Later I found an O (n) algorithm. Because both arrays are sorted. Therefore, only one traversal is required. First, set two subscripts, initialize them as the starting addresses of the two arrays respectively, and push forward in sequence. The advancing rule is to compare the numbers in two arrays. The subscript of the small array is pushed forward until the subscript of any array reaches the end of the array. If the same number is not touched yet, it indicates that the array does not have the same number.

  1. Bool findcommon2 (int A [], int size1, int B [], int size2)
  2. {
  3. Int I = 0, j = 0;
  4. While (I <size1 & J <size2)
  5. {
  6. If (A [I] = B [J])
  7. Return true;
  8. If (A [I]> B [J])
  9. J ++;
  10. If (A [I] <B [J])
  11. I ++;
  12. }
  13. Return false;
  14. }

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.