Returns the intersection of two arrays.
Question: Give you two sorted arrays and find the intersection of the two arrays.
For example, if A = 1 3 4 5 7, B = 2 3 5 8 9, then the intersection is 3 5.
Ideas:
1. Each time A value is obtained from array B, and then compared one by one in array A. If there is an equal value, it is saved. The complexity of this algorithm is O (MN). M, and N is the length of array a B, respectively.
2. because a B is out of order, after each value is taken from array B, you can use the binary search to check whether the value of B exists in array, in this way, the complexity becomes O (N lg M ). Here, if N is greater than M, you can take A value from A and then judge whether there is A value in B. In this way, the complexity is O (M lg N ).
3. use hashtable. first, store the value in A in hashtable, and then judge whether the value in each B exists in A. Because the average complexity of hashtable search is O (1, the complexity of the entire algorithm is O (N), but the space complexity here is O (M ). However, this method is suitable for small arrays. If the array is large, hashtable will see collision, so that the average search complexity is no longer O (1 ).
Method:
Because array a B is out of order, we can use two "Pointers" to point to the headers of the two arrays respectively. If one of them is smaller than the other, move the pointer of the small array; if they are equal, the value is saved in the conset. Then, the pointer of the two arrays is moved at the same time. This operation continues until a pointer has exceeded the array range.
[Java]View plaincopy
- Public writable list Intersection (int [] A, int [] B ){
- If (A = null | B = null | A. length = 0 | B. length = 0) return null;
- Shortlist List = new external list ();
- Int pointerA = 0;
- Int pointerB = 0;
- While (pointerA <A. length & pointerB <B. length ){
- If (A [pointerA] <B [pointerB]) pointerA ++;
- Else if (A [pointerA]> B [pointerB]) pointerB ++;
- Else {
- List. add (A [pointerA]);
- PointerA ++;
- PointerB ++;
- }
- }
-
- Return list;
-
- }
We can see from the above algorithm that the complexity of this algorithm is O (N + M ).Extension:
Calculate the union of the two Arrays for the two sorted arrays.