Huawei hands-on exercises -- sum of two Arrays

Source: Internet
Author: User

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;
}
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.