public int[] arrayIntersection(int[] a, int[] b) {
int[] togetherArray = new int[20];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
//System.out.println(a[i]);
togetherArray[i] = a[i];
}
}
}
return togetherArray;
}
public int[] arrayUnion(int[] a, int[] b) {
int[] tempArray = new int[a.length+b.length];//创建接受数组且数组的最大的值也就是这么多
for (int i = 0; i < a.length; i++) {
tempArray[i] = a[i];
} //拷贝a 再把b里面有但是在a里面没有的拷贝到这个tempArray里面
int tempCounter = a.length;
int flag = 0; //标志
for (int i = 0; i < b.length; i++) {
flag = 0;
for (int j = 0; j < a.length; j++) {
if (a[j] == b[i]) {
flag = 1;
//System.out.print(b[i]+" ");//测试已经找到
break;//一样的break
}
}
if (flag == 0) {
//System.out.println(i+" hha ");
//System.out.println(b[i]);
//System.
//System.out.println(b[i]);
tempArray[tempCounter] = b[i];
tempCounter=tempCounter+1;
//System.out.print(tempCounter);
}
}
//System.out.println(tempCounter+"hahah");
for (int i = 0; i < tempCounter; i++) {
System.out.print(tempArray[i]+" ");
}
return null;
}
Java 实现两数组的交集(Intersection)和并集(Union)
最新推荐文章于 2024-08-06 15:13:56 发布