`

两个数组合并

    博客分类:
  • Java
阅读更多

public static void main(String[] args) {

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

int b[] = { 4, 5, 6, 7, 8 };

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

// 连接两个数组

for (int i = 0; i < a.length; i++) {

temp[i] = a[i];

}

for (int i = 0; i < b.length; i++) {

temp[a.length + i] = b[i];

}

// 连接数组完成,开始清除重复元素

int size = temp.length;

for (int i = 0; i < temp.length; i++) {

if (temp[i] != -1) {

for (int j = i + 1; j < temp.length; j++) {

if (temp[i] == temp[j]) {

temp[j] = -1;// 将发生重复的元素赋值为-1

size--;

}

}

}

}

int[] result = new int[size];

for (int i = 0, j = 0; j < size && i < temp.length; i++, j++) {

if (temp[i] == -1) {

j--;

} else {

result[j] = temp[i];

}

}

// 打印结果

System.err.println(Arrays.toString(result));

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics