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

📅  最后修改于: 2022-05-13 02:24:09.096000             🧑  作者: Mango

PHP程序从两个已排序的数组中找到最接近的对

给定两个已排序的数组和一个数字 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

PHP
= 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--;
             
        // move to the greater side
        else
            $l++;
    }
 
    // Print the result
    echo "The closest pair is [", $ar1[$res_l], ", ", $ar2[$res_r], "] \n";
}
 
    // Driver Code
    $ar1 = array(1, 4, 5, 7);
    $ar2 = array(10, 20, 30, 40);
    $m = count($ar1);
    $n = count($ar2);
    $x = 38;
    printClosest($ar1, $ar2, $m, $n, $x);
 
// This code is contributed by anuj_67.
?>


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

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