1. Description of the problem
There are two ordered integer arrays A and B (no repeating elements), their lengths are Lena and LenB, and their common elements are found.
For example: a = 0,1,3,5,7,9,11;b = 2,3,4,7,11;
The intersection of them is {3,7,11}.
2. Method of Thinking
There are many ways to find the intersection, but the length of the array can affect the efficiency of the algorithm.
2.1 The length is equivalent, the algorithm can be taken 2.1.12 Way Merge
For array A-B, iterate through the array from the I,J, respectively. If the current position of a[i] equals b[j], then these two numbers are an intersection of two arrays, recorded and continue to traverse, if a[i] is greater than b[j], then continue to traverse array B, otherwise iterate over array a. The code is as follows:
//Two Way Merge method int Comnun_merge (int a[],int Lena,int b[],int lenb,int *comlst) {int i=0 , J=0 , K=0 ; while (I < LenA && J < LenB) {if (a[i] = = B[j]) {comlst[k++] = A[i]; i++; j + +; } else if (A[i] > B[j]) {j ++; } else i++; } return K;}
2.1.2 Hash Lookup
Loop through one of the arrays and store the elements in a hash table, then iterate over the other array and hash the query. If present, it is an intersection of two arrays, recorded and continued until the end of the query.
//hash Table lookup method, this method can be unordered, But required element is positive int comnum_hash (int A[],int lena,int b[],int lenb,int *comlst) {int Hashtb[max_int] = {0 },i,j,k=0 ; for (i = 0 ; i < LenA; i++) hashtb[a[i]] = 1 ; for (j = 0 ; J < LenB; J + +) {if (hashtb[b[j]] = = 1 ) comlst[k++] = B[J]; } return K;}
2.2 Two array lengths differ significantly
In this case, you might consider using a binary lookup method. The smaller array is traversed first, and then the value of the element is looked up in a larger array of lengths.
//Two-point lookup methodintComnum_binary (intA[],intLenA,intB[],intLenB,int*COMLST) {inti,j,k=0; for(i =0; i < LenA; i++) {intL=0, r=lenb-1, Mid; while(L <= R) {mid = (l+r)/2;if(A[i] < B[mid]) R = mid-1;Else if(A[i] > B[mid]) L = mid +1;Else{comlst[k++] = A[i]; Break; } } }returnK;}
Finding the intersection of two ordered integer arrays