假设我们有三个排序的数组A,B和C,以及分别来自A,B和C的三个元素i,j和k,使得max(| A [i] – B [i] |,| B [j] – C [k] |,| C [k] – A [i] |)被最小化。因此,如果A = [1、4、10],B = [2、15、20]和C = [10、12],则输出元素为10、15、10,这三个分别来自A,B和C。
假设A,B和C的大小分别为p,q和r。现在按照以下步骤解决这个问题-
i:= 0,j:= 0和k:= 0
现在在i <p和j <q和k <r时执行以下操作。
找出A [i],B [j]和C [k]的最小值和最大值
计算差异:= max(X,Y,Z)-min(A [i],B [j],C [k])
如果结果小于当前结果,则将其更改为新结果
递增包含最小值的数组的指针。
#include <iostream> using namespace std; void getClosestElements(int A[], int B[], int C[], int p, int q, int r) { int diff = INT_MAX; int i_final =0, j_final = 0, k_final = 0; int i=0,j=0,k=0; while (i < p && j < q && k < r) { int min_element = min(A[i], min(B[j], C[k])); int max_element = max(A[i], max(B[j], C[k])); if (max_element-min_element < diff){ i_final = i, j_final = j, k_final = k; diff = max_element - min_element; } if (diff == 0) break; if (A[i] == min_element) i++; else if (B[j] == min_element) j++; else k++; } cout << A[i_final] << " " << B[j_final] << " " << C[k_final]; } int main() { int A[] = {1, 4, 10}; int B[] = {2, 15, 20}; int C[] = {10, 12}; int p = sizeof A / sizeof A[0]; int q = sizeof B / sizeof B[0]; int r = sizeof C / sizeof C[0]; cout << "Closest elements are: "; getClosestElements(A, B, C, p, q, r); }
输出结果
Closest elements are: 10 15 10