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