数组A,有一千万个数,数组B同样也有千万多个数,然后从A和B当中随意找一个数字A1和B1,A1-B的绝对值是C,保证C最小。求A1和B1

        $a = [-11, -5, -9, -3, -2, -1];
        $b = [-20, -13, -4, 6, 77, 200];

        $key = $a[rand(0, count($a) - 1)];
        sort($b);
        echo "\n=====================\n";
        print_r($b);
        echo $key . "\n=====================\n";
        if (count($b) > 1) {
            foreach ($b as $k => $v) {

                if ($key == $v) {
                    $minAbs = 0;
                    echo "loca:{$k,abs{$minAbs} \n";
                    exit;
                }
                if ($key > $v) {
// echo $v."," ;
                } else {
                    $last = $b[$k - 1];
                    $next = $b[$k + 1];
                    $curr = $b[$k];
                    echo "\n" . $last, "\t <", $curr, ">\t", $next;
                    $min = min(abs($key - $next), abs($key - $curr), abs($key - $last));
                    echo "\n min abs:" . $min;
                    exit;

                }
            }
        } else {
            echo abs($key - $a[0]);
        }

你可能感兴趣的:(PHP)