如何在 Java 中检查给定的数组是否不相交?
在 Java 中,数组是一个对象。它是一种非原始数据类型,用于存储相同数据类型的值。
根据问题陈述,我们必须检查给定的数组是否不相交。如果两个数组没有共同的元素,则称数组不相交,即第一个数组中的元素不等于第二个数组中的元素。
让我们探索本文,看看如何使用 Java 编程语言来实现这一点。
为您展示一些实例
实例 1
Suppose the original two arrays are {13, 44, 11, 19, 3} and {7, 12, 1, 5}.
在检查给定两个数组中的不相交元素后,结果将为 -
The arrays are disjoint
实例 2
Suppose the original two arrays are {22, 4, 15, 9, 53} and {71, 4, 1, 22}
在检查给定两个数组中的不相交元素后,结果将为 -
The arrays are not disjoint
实例 3
Suppose the original two arrays are {15, 14, 91,9, 1} and {24, 2, 21, 85}
在检查给定两个数组中的不相交元素后,结果将为 -
The arrays are disjoint
算法
步骤 1 - 声明并初始化一个整数数组。
步骤 2 - 声明布尔值以检查是否不相交。
步骤 3 - 声明两个 for 循环,一个嵌套在另一个里面。
步骤 4 - 检查 if(arr1[i] == arr2[j])
步骤 5 - if(arr1[i] == arr2[j]) 则打印数组不相交。
步骤 6 - 否则打印数组不相交。
语法
要获取数组的长度(数组中的元素数量),数组有一个内置属性,即length。
下面指的是它的语法 -
array.length
其中“array”指的是数组引用。
多种方法
我们提供了不同方法的解决方案。
使用数组的静态初始化
使用用户定义的方法
让我们逐一查看程序及其输出。
方法 1:使用数组的静态初始化
示例
在这种方法中,数组元素将在程序中初始化。然后根据算法检查给定的数组是否不相交。
import java.util.*;
public class Main{
//main method
public static void main(String[] args) {
//Declare and initialize two array elements
int arr1[] = { 15, 14, 91,9, 1 };
int arr2[] = { 24, 2, 21, 85 };
//declare boolean to check for disjoint or not
boolean flag = false;
//logic implementation
for(int i = 0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i] == arr2[j]){
flag = true;
break;
}
}
}
System.out.println("First array is: "+Arrays.toString(arr1));
System.out.println("Second array is: "+Arrays.toString(arr2));
// print array are disjoint
if(!flag) {
System.out.println("The arrays are disjoint");
return;
}
// print array are not disjoint
else {
System.out.println("The arrays are not disjoint");
}
}
}
输出
First array is: [15, 14, 91, 9, 1] Second array is: [24, 2, 21, 85] The arrays are disjoint
方法 2:使用用户定义的方法
示例
在这种方法中,数组元素将在程序中初始化。然后通过将数组作为参数传递来调用用户定义的方法,并在方法内部根据算法检查给定的数组是否不相交。
import java.util.*;
public class Main{
//main method
public static void main(String[] args) {
//Declare and initialize two array elements
int arr1[] = { 22, 4, 15, 9, 53 };
int arr2[] = { 71, 4, 1, 22 };
System.out.println("First array is: "+Arrays.toString(arr1));
System.out.println("Second array is: "+Arrays.toString(arr2));
//calling user defined method
func(arr1, arr2);
}
//declaring user defined method
static void func(int []arr1, int []arr2){
//declare boolean to check for disjoint or not
boolean flag = false;
//logic implementation
for(int i = 0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i] == arr2[j]){
flag = true;
break;
}
}
}
// print array are disjoint
if(!flag) {
System.out.println("The arrays are disjoint");
return;
}
// print array are not disjoint
else{
System.out.println("The arrays are not disjoint");
}
}
}
输出
First array is: [22, 4, 15, 9, 53] Second array is: [71, 4, 1, 22] The arrays are not disjoint
在本文中,我们探讨了如何使用 Java 编程语言检查给定的数组是否不相交。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP