gpt4 book ai didi

java - 如何合并 2 个数组?

转载 作者:行者123 更新时间:2023-12-05 08:57:54 26 4
gpt4 key购买 nike

我正在尝试以这种方式合并 2 个数组:

int[] arr1 = { 1, 3, 9, 5 };
int[] arr2 = { 7, 0, 5, 4, 3 };

现在我需要创建一个如下所示的新数组:

int[] merged = { 1, 3, 9, 5, 7, 0, 4 };

所以我需要将所有数字放入新数组中,但如果一个数字在两个数组中,那么它不应该重复,每个数字在合并数组中应该只有一次。

同一个数组中的数字永远不会出现两次或更多次。

这是我构建的程序:

int[] arr1 = { 1, 6, -6, -9, 3, 4, -8, -7 };
int[] arr2 = { 5, 3, 2, 1, 70, 6, 7, -9, 99, 81 };

int counter = arr1.length;

boolean b = true;

for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length && b == true; j++) {
if (arr1[i] == arr2[j])
b = false;
}

if (b == true) {
counter++;
}

b = true;
}

System.out.println(counter);

由于某种原因它不起作用..

我正在尝试编写没有内置函数或列表的程序,谢谢。

最佳答案

不使用 ListSet 或任何第三方库(Java 101 作业就绪):

int[] arr1 = { 1, 6, -6, -9, 3, 4, -8, -7 };
int[] arr2 = { 5, 3, 2, 1, 70, 6, 7, -9, 99, 81 };

// Create a boolean array with the same length as the first array.
boolean[] duplicates = new boolean[arr1.length];
// Counter for how many duplicates we found.
int numDuplicates = 0;

// Loop through the first array and get all duplicates.
for (int i = 0; i < arr1.length; i++) {
boolean duplicate = false;
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
duplicate = true;
numDuplicates++;
break;
}
}
duplicates[i] = duplicate;
}

// The length of the merged array will be the two lengths subtracted by the number of
// duplicates we found.
int[] mergedArray = new int[arr1.length + arr2.length - numDuplicates];
int index = 0;

// loop through the first array. Don't add it to the merged array if it is a duplicate.
for (int i = 0; i < arr1.length; i++) {
if (!duplicates[i]) {
mergedArray[index] = arr1[i];
index++;
}
}

// loop through the second array and add all items.
for (int i = 0; i < arr2.length; i++) {
mergedArray[index] = arr2[i];
index++;
}

// optional. sort array
Arrays.sort(mergedArray);

System.out.println(Arrays.toString(mergedArray));

输出:

[-9, -8, -7, -6, 1, 2, 3, 4, 5, 6, 7, 70, 81, 99]

使用设置:

public static int[] mergeArrays(int[] arr1, int[] arr2) {
Set<Integer> set = new HashSet<Integer>();
for (int x : arr1) {
set.add(x);
}
for (int x : arr2) {
set.add(x);
}
int[] result = new int[set.size()];
int index = 0;
for (Iterator<Integer> it = set.iterator(); it.hasNext();) {
result[index] = it.next();
index++;
}
return result;
}

使用列表:

public static int[] mergeArrays(int[] arr1, int[] arr2) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0, length = arr1.length; i < length; i++) {
list.add(arr1[i]);
}
for (int i = 0, length = arr2.length; i < length; i++) {
if (!list.contains(arr2[i])) {
list.add(arr2[i]);
}
}
int length = list.size();
int[] result = new int[length];
for (int i = 0; i < length; i++) {
result[i] = list.get(i);
}
return result;
}

关于java - 如何合并 2 个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28145962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com