本文介绍了java中2个数组的联合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码
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 中使用任何预定义的接口和方法.我的答案应该是{1,2,4}
I am using this output to find union of 2d array .but output which i am getting is wrong . i don't want 2 use any predefined interface and method in java .my answer should be{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中2个数组的联合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!