java两个数组中不同的数字_java编程将a,b数组中不同的数字保存到一个新的数组中...

展开全部

建立一32313133353236313431303231363533e4b893e5b19e31333337623464个临时数组 定义一个length来记录新加入的元素个数 然后把a b 的元素逐个加入到新数组中 加入前先用Arrays.binarySearch 检查新数组中是否已经有该元素 最后返回

以下代码仅供参考import java.util.Arrays;

public class TestCircle {

public static void main(String args[]) {

int[] a = new int[] { 1, 3, 5, 2, 9, 5 };

int[] b = new int[] { 2, 5, 7, 10, 9, 11 };

int[] temp = addArray(a, b);

System.out.print("[");

for (int i : temp) {

System.out.print(i + " ");

}

System.out.print("]");

}

static int[] addArray(int[] a, int[] b) {

int[] temp = new int[a.length + b.length];

int length = 0;

for (int i : a) {

Arrays.sort(temp);

if (Arrays.binarySearch(temp, i) 

temp[temp.length - length - 1] = i;

length++;

}

}

for (int i : b) {

Arrays.sort(temp);

if (Arrays.binarySearch(temp, i) 

temp[temp.length - length - 1] = i;

length++;

}

}

return Arrays.copyOfRange(temp, temp.length - length, temp.length);

}

}

若你能保证a中的元素都是无重复的话   可以简化成以下import java.util.Arrays;

public class TestCircle {

public static void main(String args[]) {

int[] a = new int[] { 1, 3, 5, 2, 9 };

int[] b = new int[] { 2, 5, 7, 10, 9, 11 };

Arrays.sort(a);

int[] temp = addArray(a, b);

System.out.print("[");

for (int i : temp) {

System.out.print(i + " ");

}

System.out.print("]");

}

/**

* 这里a数组必须是有序不重复的

*/

static int[] addArray(int[] a, int[] b) {

int[] temp = Arrays.copyOf(a, a.length + b.length);

int length = a.length;

for (int i : b) {

if (Arrays.binarySearch(a, i) 

temp[length] = i;

length++;

}

}

return Arrays.copyOf(temp, length);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值