📌  相关文章
📜  用于从两个排序数组中查找最近对的Python程序

📅  最后修改于: 2022-05-13 01:56:56.456000             🧑  作者: Mango

用于从两个排序数组中查找最近对的Python程序

给定两个排序数组和一个数字 x,找到总和最接近 x 的对,并且该对在每个数组中都有一个元素
给定两个数组 ar1[0…m-1] 和 ar2[0..n-1] 以及一个数字 x,我们需要找到对 ar1[i] + ar2[j] 使得 (ar1 [i] + ar2[j] – x) 是最小值。
例子:

Input:  ar1[] = {1, 4, 5, 7};
        ar2[] = {10, 20, 30, 40};
        x = 32      
Output:  1 and 30

Input:  ar1[] = {1, 4, 5, 7};
        ar2[] = {10, 20, 30, 40};
        x = 50      
Output:  7 and 40

Python3
# Python3 program to find the pair from
# two sorted arrays such that the sum
# of pair is closest to a given number x
import sys
 
# ar1[0..m-1] and ar2[0..n-1] are two
# given sorted arrays and x is given
# number. This function prints the pair
# from both arrays such that the sum
# of the pair is closest to x.
def printClosest(ar1, ar2, m, n, x):
 
    # Initialize the diff between
    # pair sum and x.
    diff = sys.maxsize
 
    # res_l and res_r are result
    # indexes from ar1[] and ar2[]
    # respectively. Start from left
    # side of ar1[] and right side of ar2[]
    l = 0
    r = n-1
    while(l < m and r >= 0):
     
    # If this pair is closer to x than
    # the previously found closest,
    # then update res_l, res_r and diff
        if abs(ar1[l] + ar2[r] - x) < diff:
            res_l = l
            res_r = r
            diff = abs(ar1[l] + ar2[r] - x)
     
 
    # If sum of this pair is more than x,
    # move to smaller side
        if ar1[l] + ar2[r] > x:
            r = r-1
        else: # move to the greater side
            l = l + 1
     
 
    # Print the result
    print("The closest pair is [",
         ar1[res_l], ", ", ar2[res_r], "]")
 
# Driver program to test above functions
ar1 = [1, 4, 5, 7]
ar2 = [10, 20, 30, 40]
m = len(ar1)
n = len(ar2)
x = 38
printClosest(ar1, ar2, m, n, x)
 
# This code is contributed by Smitha Dinesh Semwal


输出:
The closest pair is [ 7 ,  30 ]

有关更多详细信息,请参阅有关从两个排序数组中查找最近对的完整文章!