参数是函数的{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最喜欢的语句来自Java的Character类:(1 << Character.PARAGRAPH_SEPARATOR)) >> type PARAGRAPH_SEPARATOR是字节,type是整数。这句话中的操作员,他们做什么?如何以及在哪里可以使用这些运算符?这是oracles java.lang.Character文档。该类中…
JAVA:字节码和二进制有什么区别? - javajava字节代码(已编译的语言,也称为目标代码)与机器代码(当前计算机的本机代码)之间有什么区别?我读过一些书,他们将字节码称为二进制指令,但我不知道为什么。 参考方案 字节码是独立于平台的,在Windows中运行的编译器编译的字节码仍将在linux / unix / mac中运行。机器代码是特定于平台的,如果在Windows x86中编译,则它将仅在Win…
java:继承 - java有哪些替代继承的方法? java大神给出的解决方案 有效的Java:偏重于继承而不是继承。 (这实际上也来自“四人帮”)。他提出的理由是,如果扩展类未明确设计为继承,则继承会引起很多不正常的副作用。例如,对super.someMethod()的任何调用都可以引导您通过未知代码的意外路径。取而代之的是,持有对本来应该扩展的类的引用,然后委托给它。这是与Eric…
Java:BigInteger,如何通过OutputStream编写它 - java我想将BigInteger写入文件。做这个的最好方式是什么。当然,我想从输入流中读取(使用程序,而不是人工)。我必须使用ObjectOutputStream还是有更好的方法?目的是使用尽可能少的字节。谢谢马丁 参考方案 Java序列化(ObjectOutputStream / ObjectInputStream)是将对象序列化为八位字节序列的一种通用方法。但…
Java-如何将此字符串转换为日期? - java我从服务器收到此消息,我不明白T和Z的含义,2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么? java大神给出的解决方案 这是ISO 8601标准。您可以使用SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM…