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 < m; k++) {
System.out.print(arr1[k] + " ");
}
System.out.print("
");
System.out.print("Array 2: ");
for(int k = 0; k < n; k++) {
System.out.print(arr2[k] + " ");
}
System.out.print("
");
System.out.print("Intersection of two arrays is: ");
while (i < m && j < n) {
if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr1[i])
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 < m; k++) {
System.out.print(arr1[k] + " ");
}
System.out.print("
");
System.out.print("Array 2: ");
for(int k = 0; k < n; k++) {
System.out.print(arr2[k] + " ");
}
然后,使用 while 循环显示两个数组的交集,即它们通用的元素。展示这一过程的代码片段如下所示。
System.out.print("Intersection of two arrays is: ");
while (i < m && j < n) {
if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr1[i])
j++;
else {
System.out.print(arr2[j++]+" ");
i++;
}
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP