java中两个整型数组求交集_Java中两个数组的交集

两个数组的交集导致两个数组中都包含这些元素。如果元素仅在数组之一中,则在交集中不可用。一个例子如下:Array 1 = 1 2 5 8 9

Array 2 = 2 4 5 9

Intersection = 2 5 9

给出了一个演示Java中两个排序数组的交集的程序,如下所示。

示例

public class Example {

public static void main(String args[]) {

int arr1[] = {2, 4, 6, 8, 9};

int arr2[] = {1, 3, 4, 5, 6, 8, 9};

int m = arr1.length;

int n = arr2.length;

int i = 0, j = 0;

System.out.print("Array 1: ");

for(int k = 0; k 

System.out.print(arr1[k] + " ");

}

System.out.print("\n");

System.out.print("Array 2: ");

for(int k = 0; k 

System.out.print(arr2[k] + " ");

}

System.out.print("\n");

System.out.print("Intersection of two arrays is: ");

while (i 

if (arr1[i] 

i++;

else if (arr2[j] 

j++;

else {

System.out.print(arr2[j++]+" ");

i++;

}

}

}

}

上面程序的输出如下。

输出结果Array 1: 2 4 6 8 9

Array 2: 1 3 4 5 6 8 9

Intersection of two arrays is: 4 6 8 9

现在让我们了解上面的程序。

首先,打印两个数组的值。演示此过程的代码段如下所示。System.out.print("Array 1: ");

for(int k = 0; k 

System.out.print(arr1[k] + " ");

}

System.out.print("\n");

System.out.print("Array 2: ");

for(int k = 0; k 

System.out.print(arr2[k] + " ");

}

然后,使用while循环显示两个数组的交集,即它们的公共元素。演示此过程的代码段如下所示。System.out.print("Intersection of two arrays is: ");

while (i 

if (arr1[i] 

i++;

else if (arr2[j] 

j++;

else {

System.out.print(arr2[j++]+" ");

i++;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值