展开全部
建立一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);
}
}