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 partition list <Integer> intersection (int [] A, int [] B ){
- If (A = null | B = null | A. length = 0 | B. length = 0) return null;
- Counter list <Integer> list = new counter list <Integer> ();
- 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.
How are the intersection of two arrays?
Is a set composed of two public elements. For example, elements A of A set are 1, 2, and 3. Elements B of A set are 3, 4, and 5. Element 3 is a combination of the two sets. Therefore, a collection composed of element 3 is the intersection of the two sets. I don't know, but I'm tired of typing on my cell phone.
How are the intersection of two arrays?
Write an array, store the characters in the first string into the array according to char, and find each character in the second string in the array to see if it exists.