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:
- Bool findcommon (int A [], int size1, int B [], int size2)
- {
- Int I;
- For (I = 0; I <size1; I ++)
- {
- Int start = 0, end = size2-1, mid;
- While (start <= end)
- {
- Mid = (start + end)/2;
- If (A [I] = B [Mid])
- Return true;
- Else if (a [I] <B [Mid])
- End = mid-1;
- Else
- Start = Mid + 1;
- }
- }
- Return false;
- }
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.
- Bool findcommon2 (int A [], int size1, int B [], int size2)
- {
- Int I = 0, j = 0;
- While (I <size1 & J <size2)
- {
- If (A [I] = B [J])
- Return true;
- If (A [I]> B [J])
- J ++;
- If (A [I] <B [J])
- I ++;
- }
- Return false;
- }