How to implement the two sum algorithm to find two values in a list that add up to target with PHP

2 Answers

0 votes
function twoSum($array, $target) {
    for ($i = 0; $i < count($array); $i++) {
        for ($j = $i + 1; $j < count($array); $j++) {
            if ($array[$i] + $array[$j] == $target) {
                return array($i, $j);
            }
        }
    }
    return array();
}

$array = array(1, 5, 7, 6, 4, 3, 2);
$target = 9;
$indexes = twoSum($array, $target);

if (count($indexes) == 2) {
    echo strval($indexes[0]) . " " . strval($indexes[1]);
}
else {
    echo "Not found";
}




/*
run:

1 4

*/

 



answered Jul 18, 2023 by avibootz
0 votes
function twoSum($array, $target) {
    $hmap = array();
    for ($i = 0; $i < count($array); $i++) {
        $complement = $target - $array[$i];
        if (array_key_exists($complement,$hmap)) {
            return array($hmap[$complement], $i);
        }
        else {
            $hmap[$array[$i]] = $i;
        }
    }
    return array();
}

$array = array(1, 5, 7, 6, 4, 3, 2);
$target = 9;
$indexes = twoSum($array, $target);

if (count($indexes) == 2) {
    echo strval($indexes[0]) . " " . strval($indexes[1]);
}
else {
    echo "Not found";
}







/*
run:

1 4

*/

 



answered Jul 18, 2023 by avibootz
...