Java程序查找两个数组之间的共同元素
时间:2020-01-09 10:35:27 来源:igfitidea点击:
在这篇文章中,我们将看到一个Java程序来查找两个数组之间的公共元素。在编写此程序时,可能会要求我们不要使用任何内置的Java方法,在这种情况下,我们可以使用for循环迭代数组并列出公共元素。
如果允许使用任何内置方法,则可以使用Java中Set的keepAll()方法来获取两个数组之间的公共元素。
查找两个数组之间的共同元素–迭代
在此解决方案中,我们可以在外循环中迭代一个数组,并使用内循环将每个元素与另一个数组的所有元素进行比较。
public class CommonElement {
public static void main(String[] args) {
int[] arr1 = {3, 10, 1, 0, 9};
int[] arr2 = {32, 5, 10, 6, 9, 1};
for(int i = 0; i < arr1.length; i++){
for(int j = 0; j < arr2.length; j++){
if(arr1[i] == arr2[j]){
System.out.print(arr1[i] + " ");
break;
}
}
}
}
}
输出:
10 1 9
查找两个排序数组之间的公共元素
上面的解决方案是O(N2),如果可以对数组进行排序,则可以将时间减少到O(2NLogN + N)。
对数组进行排序后,可以在while循环中比较数组的元素,如果元素不相等,则仅递增数组索引中的一个,否则在两个数组中递增索引。
public class CommonElement {
public static void main(String[] args) {
int[] arr1 = {6, 8, 1, 0, 9};
int[] arr2 = {34, 2, 1, 9, 12, 67, 0};
findCommonElement(arr1, arr2);
}
public static void findCommonElement(int[] arr1, int[] arr2){
// sort arrays
Arrays.sort(arr1);
Arrays.sort(arr2);
int lengthArr1 = arr1.length;
int lengthArr2 = arr2.length;
int i = 0, j = 0;
while(i < lengthArr1 && j < lengthArr2){
// compare and increment
if(arr1[i] > arr2[j]){
j++;
}else if (arr2[j] > arr1[i]){
i++;
}else{
//Print common element
System.out.print(arr1[i] + " ");
i++;
j++;
}
}
}
}
输出:
0 1 9
使用HashSet查找两个数组之间的公共元素
我们还可以使用HashSet的keepAll()方法来查找两个数组之间的公共元素。
keepAll()方法仅保留Set中包含在传递的Collection中的那些元素。
public class CommonElement {
public static void main(String[] args) {
int[] arr1 = {3, 10, 1, 0, 9};
int[] arr2 = {32, 5, 10, 6, 9, 1};
findCommonElement(arr1, arr2);
}
public static void findCommonElement(int[] arr1, int[] arr2){
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
// adding elements from array1
for(int i : arr1){
set1.add(i);
}
// adding elements from array2
for(int i : arr2){
set2.add(i);
}
set1.retainAll(set2);
System.out.println("Common elements- " + set1);
}
}
输出:
Common elements- [1, 9, 10]

