gpt4 book ai didi

java - java中两个数组的并集没有得到想要的结果

转载 作者:行者123 更新时间:2023-12-02 06:04:12 24 4
gpt4 key购买 nike

参数是函数的{1,2,3}和{2,3,4}。输出应该是{1,2,3,4}。我不明白我在这里做错了什么。我得到的输出是 {1,1,2,4,0,0}.. 请帮忙,谢谢

void test(int x[],int y[]){
int i =0;
int j= 0;
int f =0;
int total = x.length+ y.length;
int a[];
a = new int[total];
while(i<x.length && j<y.length){
if(x[i]<y[j]){
a[f] = x[i];
i++;
f++;
}else if(x[i]>y[j]){
a[f] = y[j];
j++;
f++;
}else{
a[f] = x[j];
i++;
j++;
f++;
}
}
while(i<x.length){
a[f] = x[i];
i++;
f++;
}
while(j<y.length){
a[f] = y[j];
j++;
f++;
}

for(int w=0;w<a.length;w++){
System.out.print(a[w]);
System.out.print(" ");
}



}

最佳答案

引用此页面:https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/

// Java program to find union of 
// two sorted arrays

class FindUnion
{
/* Function prints union of arr1[] and arr2[]
m is the number of elements in arr1[]
n is the number of elements in arr2[] */
static int printUnion(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while (i < m && j < n)
{
if (arr1[i] < arr2[j])
System.out.print(arr1[i++]+" ");
else if (arr2[j] < arr1[i])
System.out.print(arr2[j++]+" ");
else
{
System.out.print(arr2[j++]+" ");
i++;
}
}

/* Print remaining elements of
the larger array */
while(i < m)
System.out.print(arr1[i++]+" ");
while(j < n)
System.out.print(arr2[j++]+" ");

return 0;
}

public static void main(String args[])
{
int arr1[] = {1, 2, 4, 5, 6};
int arr2[] = {2, 3, 5, 7};
int m = arr1.length;
int n = arr2.length;
printUnion(arr1, arr2, m, n);
}
}

关于java - java中两个数组的并集没有得到想要的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55952211/

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