Question:
Calculate the sum and difference of the two Arrays: remove the same elements in the two arrays and store the elements in the two arrays in A new array. The elements in array A must be before the elements in array B.
For example, input: int [] a = {1, 2, 4, 7, 6, 9 };
Int [] B = {2, 4, 3, 10 };
Output: int [] c = {1, 7, 6, 9, 3, 10 };
Analysis: removing the same elements requires mutual comparison, and then inserting different elements into the new array successively. Therefore, I will focus on comparison, which may be inefficient, you can share some good ideas;
The Code is as follows:
Package com. wenj. test;
Import java. util. ArrayList;
Import java. util. List;
/*
* Calculate the sum and difference of the two Arrays: remove the same elements in the two arrays and store the elements in the two arrays in a new array.
* The element in array A must be before the element in array B.
*/
Public class TestGetNewArr {
Public static void main (String args []) {
Int [] a = {1, 2, 4, 7, 6, 9 };
Int [] B = {2, 4, 3, 10 };
Int [] c;
TestGetNewArr tg = new TestGetNewArr ();
C = tg. getNewArr (a, B );
For (int I = 0; I <c. length; I ++ ){
System. out. print (c [I] + "");
}
}
Public int [] getNewArr (int [] a, int [] B ){
List <Integer> aL = new ArrayList <Integer> ();
For (int I = 0; I <a. length; I ++) {// compared with B, if the same, it is not placed in the new array.
Boolean isExist = false;
For (int j = 0; j <B. length; j ++ ){
If (a [I] = B [j]) {
IsExist = true;
}
}
If (! IsExist ){
AL. add (a [I]);
}
}
For (int I = 0; I <B. length; I ++ ){
Boolean isExist = false;
For (int j = 0; j <a. length; j ++ ){
If (B [I] = a [j]) {
IsExist = true;
}
}
If (! IsExist ){
AL. add (B [I]);
}
}
Int [] c = new int [aL. size ()];
For (int I = 0; I <c. length; I ++ ){
C [I] = aL. get (I );
}
Return c;
}
}