用於在三個已排序陣列中查詢公共元素的 Python 程式?
這裡我們首先建立 3 個數組,即使用者輸入的未排序陣列,然後對所有 3 個未排序陣列進行排序。陣列的大小為 n1、n2、n3。每個陣列的起始地址為 0。i=0、j=0、k=0,然後遍歷三個陣列的所有元素並檢查三個陣列的元素是否相同,如果相同,則列印該元素,否則轉到下一個元素。
示例
A = {1, 2, 3, 4, 5}
B = {2, 5, 12, 22, 7}
C = {1, 9, 2, 89, 80}
輸出
2
演算法
commonele(A1,A2,A3,n1,n2,n3) /* A1, A2, A3 are three integer sorted array and size1, size2, size3 are the sizes of the array.*/ Step 1: Initialize the starting indexes for A1, A2, A3. i=0, j=0, k=0 Step 2: iterate through three Arrays while arrays are nonempty. While(i<size1 && j<size2 && k<size3) Step 3: then check every value of A1,A2,A3.if the value are same then print otherwise move ahead in all arrays. Step 4: End While
示例程式碼
# To print common elements in three sorted arrays
def commonele (X, Y, Z, n1, n2, n3):
i, j, k = 0, 0, 0
print("Common elements are ::>")
while (i < n1 and j <n2 and k< n3):
if (X[i] == Y[j] and Y[j] == Z[k]):
print (X[i])
i += 1
j += 1
k += 1
elif X[i] < Y[j]:
i += 1
elif Y[j] < Z[k]:
j += 1
else:
k += 1
# Driver program
A=list()
B=list()
C=list()
n1=int(input("Enter the size of the First List ::"))
n2=int(input("Enter the size of the Second List ::"))
n3=int(input("Enter the size of the Third List ::"))
print("Enter the Element of First List ::")
for i in range(int(n1)):
k=int(input(""))
A.append(k)
print("Enter the Element of Second List ::")
for j in range(int(n2)):
k1=int(input(""))
B.append(k1)
print("Enter the Element of Third List ::")
for j in range(int(n3)):
k1=int(input(""))
C.append(k1)
X=sorted(A)
Y=sorted(B)
Z=sorted(C)
print("First Sorted List ::>",X)
print("Second Sorted List ::>",Y)
print("Third Sorted List ::>",Z)
commonele(X, Y, Z, n1, n2, n3)
輸出
Enter the size of the First List :: 4 Enter the size of the Second List :: 4 Enter the size of the Third List :: 5 Enter the Element of First List :: 23 12 45 8 Enter the Element of Second List :: 34 8 45 120 Enter the Element of Third List :: 2 4 8 45 1 First Sorted List ::> [8, 12, 23, 45] Second Sorted List ::> [8, 34, 45, 120] Third Sorted List ::> [1, 2, 4, 8, 45] Common elements are ::> 8 45
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP