Java array intersection, union, and java array Intersection
// Calculate the intersection of two Arrays
Public static int [] SameOfTwoArrays (int [] arr1, int [] arr2 ){
// Create an empty array to store the intersection. The length of the empty array should be the minimum of the two arrays.
Int temp [] = new int [arr1.length <arr2.length? Arr1.length: arr2.length];
// Defines an int variable. The initial value is 0. It is used to add an element from the intersection array.
Int k = 0;
// The function of the for loop at the first layer is to traverse and obtain an element in two arrays. If the processing is efficient, the shorter array should be traversed.
For (int I = 0; I <arr1.length; I ++ ){
// Layer 2 for loop, traversing to get the elements of another Array
For (int j = 0; j <arr2.length; j ++ ){
// Compare the elements in the two Arrays
If (arr1 [I] = arr2 [j]) {
// If the two elements are equal, they are saved to the intersection array. The index of the intersection array needs to be increased to store the next equal element.
Temp [k ++] = arr1 [I];
// Store the position of the element found in the second-level loop equal to that in the first-level loop, such as the last element of the array.
Arr2 [j] = arr2 [arr2.length-1];
// Delete the last element
Arr2 = Arrays. copyOf (arr2, arr2.length-1 );
// End this internal loop
Break;
}
}
}
Return Arrays. copyOf (temp, k );
}
// Calculate the union of two Arrays
Public static int [] mergeArrays (int [] arr1, int [] arr2 ){
// Create an empty array to store the intersection. The length of the empty array should be the sum of the length of the two arrays.
Int [] temp = new int [arr1.length + arr2.length];
// Copy the two arrays to the temp Array
System. arraycopy (arr1, 0, temp, 0, arr1.length );
System. arraycopy (arr2, 0, temp, arr1.length, arr2.length );
// Loop at the first layer, traversing to the end of the first array
For (int I = 0; I <arr1.length; I ++ ){
// Layer 2 loop, traversing from the second array
For (int j = arr1.length; j <temp. length; j ++ ){
// If the element of the second array is equal to the element of the first array, delete the element of the second array.
If (temp [I] = temp [j]) {
// Put the elements of the second array at the end of the temp Array
Temp [j] = temp [temp. length-1];
// Delete the last element
Temp = Arrays. copyOf (temp, temp. length-1 );
Break;
}
}
}
Arrays. sort (temp );
Return temp;
}