標籤:java 華為 演算法 解決方案
題目:
求兩個數組的和差:就是去掉兩個數組中相同的元素 然後將兩個數組中的元素存放在一個新的數組中,且數組A中元素要在B數組元素之前
如:輸入: int[] a={1,2,4,7,6,9};
int[] b={2,4,3,10};
輸出: int[] c = {1, 7, 6, 9, 3, 10};
分析: 剔除相同的元素要互相比較, 然後將不同的元素先後插入新的數組中, 所以我將重點放在比較上, 有可能效率有點低, 大家有什麼好的想法可以分享下;
代碼如下:
package com.wenj.test;
import java.util.ArrayList;
import java.util.List;
/*
* 求兩個數組的和差:就是去掉兩個數組中相同的元素 然後將兩個數組中的元素存放在一個新的數組中
* 且數組A中元素要在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++){//a與b的相比,相同的則不放進新的數組中
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;
}
}