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

📅  最后修改于: 2021-05-28 03:33:26             🧑  作者: Mango

给定两个已排序的数组和一个数字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
C++
// C++ program to find the pair from two sorted arays such
// that the sum of pair is closest to a given number x
#include 
#include 
#include 
using namespace std;
  
// 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.
void printClosest(int ar1[], int ar2[], int m, int n, int x)
{
    // Initialize the diff between pair sum and x.
    int diff = INT_MAX;
  
    // res_l and res_r are result indexes from ar1[] and ar2[]
    // respectively
    int res_l, res_r;
  
    // Start from left side of ar1[] and right side of ar2[]
    int l = 0, r = n - 1;
    while (l < m && 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--;
        else // move to the greater side
            l++;
    }
  
    // Print the result
    cout << "The closest pair is [" << ar1[res_l] << ", "
         << ar2[res_r] << "] \n";
}
  
// Driver program to test above functions
int main()
{
    int ar1[] = { 1, 4, 5, 7 };
    int ar2[] = { 10, 20, 30, 40 };
    int m = sizeof(ar1) / sizeof(ar1[0]);
    int n = sizeof(ar2) / sizeof(ar2[0]);
    int x = 38;
    printClosest(ar1, ar2, m, n, x);
    return 0;
}


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

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

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。