假设我们有三个排序的数组A,B和C(它们的大小可以不同),我们必须找到计算任意三元组的最大数和最小数之间的最小绝对差(A [i],B [j], C [k]),以使它们分别位于数组A,B和C下,
因此,如果输入像A:[2,5,6,9,9,11],B:[7,10,16],C:[3,4,7,7],则输出将为1通过选择A [i] = 6 B [j] = 7和C [k] = 7,我们将获得最小差,即max(A [i],B [j],C [k])-min(A [i],B [j],C [k]))= | 7-6 | = 1
为了解决这个问题,我们将遵循以下步骤-
i:= A-1的大小
j:= B-1的大小
k:= C-1的大小
minimum_dfference:= | A [i],B [j],C [k]的最大值-A [i],B [j],C [k]的最小值|
当i与-1不相同且j与-1不相同且k与-1不相同时
k:= k-1>
j:= j-1
我:=我-1
minimum_dfference:= current_diff
current_diff:= | A [i],B [j],C [k]的最大值-A [i],B [j],C [k]的最小值|
如果current_diff <minimum_dfference不为零,则
maximum_term:= A [i],B [j],C [k]的最大值
如果A [i]与maximum_term相同,则
否则,当B [j]与maximum_term相同时,则
除此以外,
返回minimum_dfference
让我们看下面的实现以更好地理解-
def solve(A, B, C): i = len(A) - 1 j = len(B) - 1 k = len(C) - 1 minimum_dfference = abs(max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) while i != -1 and j != -1 and k != -1: current_diff = abs(max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) if current_diff < minimum_dfference: minimum_dfference = current_diff maximum_term = max(A[i], B[j], C[k]) if A[i] == maximum_term: i -= 1 elif B[j] == maximum_term: j -= 1 else: k -= 1 return minimum_dfference A = [ 2, 5, 6, 9, 11 ] B = [ 7, 10, 16 ] C = [ 3, 4, 7, 7 ] print(solve(A, B, C))
A = [ 2, 5, 6, 9, 11 ] B = [ 7, 10, 16 ] C = [ 3, 4, 7, 7 ]
输出结果
1