gpt4 book ai didi

java - java中的2个数组的联合?

转载 作者:搜寻专家 更新时间:2023-11-01 03:59:02 25 4
gpt4 key购买 nike

我的代码

class Union {

//Search Function
static boolean search(int A[], int i) {

for (int k = 0; k < A.length; k++) {
if (A[k] == i) {
return true;
}
}
return false;
}

//union
static void union(int A[][], int B[][]) {

int i = 0;
int count = 0;
int C[] = new int[A.length + B.length];

for (; i < A.length; i++) {
if (!(search(B, A[i]))) {
C[count] = A[i];
count++;
}
}

for (; i < (A.length + B.length); i++) {
C[count] = B[i - A.length];
count++;
}

System.out.println("This is Union Of 2 D Array ");
System.out.println();

for (int k = 0; k < count; k++) {
System.out.println(C[k]);
}
System.out.println();

}

public static void main(String... s) {
union(new int[]{1, 1, 1, 4,}, new int[]{1, 4, 4, 4, 1, 2});
}
}

我正在使用此输出来查找二维数组的并集。但我得到的输出是错误的。我不想 2 在 java 中使用任何预定义的接口(interface)和方法。我的回答应该是{1,2,4}

示例

A= {1,2,3,3}
B={2,3,1,1}
c={1,2,3}

最佳答案

这就是你要找的:

import java.util.Arrays;

public class Union
{

public static void main(String[] args)
{
int[] A = {1, 2, 3, 3};
int[] B = {2, 3, 1, 1};
System.out.println(Arrays.toString(unionArrays(A, B)));
}

/* Union of multiple arrays */
public static int[] unionArrays(int[]... arrays)
{
int maxSize = 0;
int counter = 0;

for(int[] array : arrays) maxSize += array.length;
int[] accumulator = new int[maxSize];

for(int[] array : arrays)
for(int i : array)
if(!isDuplicated(accumulator, counter, i))
accumulator[counter++] = i;

int[] result = new int[counter];
for(int i = 0; i < counter; i++) result[i] = accumulator[i];

return result;
}

public static boolean isDuplicated(int[] array, int counter, int value)
{
for(int i = 0; i < counter; i++) if(array[i] == value) return true;
return false;
}
}

输出:

[1, 2, 3]

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

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