Java程序查找三个已排序数组中的公共元素
三个已排序数组中的公共元素是指同时出现在这三个数组中的元素。在本文中,我们将学习如何在Java中查找三个已排序数组的公共元素。示例如下:
示例场景
Input 1: arr1 = [1, 3, 5, 7, 9] Input 2: arr2 = [2, 3, 6, 7, 9] Input 3: arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9] Output: Common elements = 3 7 9
这里,数组是数据结构,它存储固定大小的同类型元素的顺序集合。
使用迭代
在这里,我们使用while循环和if-else-if语句来查找三个已排序数组中的公共元素。
运行while循环直到每个数组的长度。在这个循环内,定义if-else-if语句,它将检查公共元素并将循环变量递增1。
示例
演示此功能的程序如下:
public class Example {
public static void main(String args[]) {
int arr1[] = {1, 4, 25, 55, 78, 99};
int arr2[] = {2, 3, 4, 34, 55, 68, 75, 78, 100};
int arr3[] = {4, 55, 62, 78, 88, 98};
int i = 0, j = 0, k = 0, x = 0;
System.out.print("Array1: ");
for(x = 0; x < arr1.length; x++) {
System.out.print(arr1[x] + " ");
}
System.out.println();
System.out.print("Array2: ");
for(x = 0; x < arr2.length; x++) {
System.out.print(arr2[x] + " ");
}
System.out.println();
System.out.print("Array3: ");
for(x = 0; x < arr3.length; x++) {
System.out.print(arr3[x] + " ");
}
System.out.println();
System.out.println("The common elements in the 3 sorted arrays are: ");
while (i < arr1.length && j < arr2.length && k < arr3.length) {
if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
System.out.print(arr1[i] + " ");
i++;
j++;
k++;
} else if (arr1[i] < arr2[j]) {
i++;
} else if (arr2[j] < arr3[k]) {
j++;
} else {
k++;
}
}
}
}
上述代码的输出如下所示:
Array1: 1 4 25 55 78 99 Array2: 2 3 4 34 55 68 75 78 100 Array3: 4 55 62 78 88 98 The common elements in the 3 sorted arrays are: 4 55 78
使用二分查找
在这种方法中,我们使用二分查找算法来查找三个已排序数组中的公共元素。
- 将数组的中间元素与当前元素进行比较。如果它们相等,则算法返回TRUE。
- 如果当前元素大于中间元素,则搜索在右半部分继续,否则在左半部分继续。
- 如果未找到元素,则方法返回FALSE。
示例
以下是说明上述方法的Java程序:
import java.util.*;
public class Example {
public static void main(String[] args) {
int[] arr1 = {1, 4, 25, 55, 78, 99};
int[] arr2 = {1, 3, 5, 78, 99};
int[] arr3 = {99, 55, 62, 78, 88, 98};
// Sorting arrays
Arrays.sort(arr1);
Arrays.sort(arr2);
Arrays.sort(arr3);
// storing common elements in a list
List<Integer> commonList = findCommonElements(arr1, arr2, arr3);
System.out.println("Common elements in the 3 sorted arrays are: " + commonList);
}
// method to find common elements from sorted arrays
public static List<Integer> findCommonElements(int[] arr1, int[] arr2, int[] arr3) {
List<Integer> result = new ArrayList<>();
for (int num : arr1) {
if (searching(arr2, num) && searching(arr3, num)) {
result.add(num);
}
}
return result;
}
// method of binary search
public static boolean searching(int[] array, int num) {
int n1 = 0;
int n2 = array.length - 1;
while (n2 >= n1) {
int mid = (n1 + n2) / 2;
if (array[mid] == num) {
return true;
} else if (array[mid] < num) {
n1 = mid + 1;
} else {
n2 = mid - 1;
}
}
return false;
}
}
上述代码的输出如下:
Common elements in the 3 sorted arrays are: [78, 99]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP