$nums = [1, 22, 3, 4, 5, 6, 9, 11, 15];
$target = 15;
function twoSum($nums, $target)
{
$res = [];
$first = null;
foreach ($nums as $k => $val) {
$another = $target - $val;
if (!empty($res)) {
if ($first == $another) {
$res[] = $k;
return $res;
}
} else {
if (in_array($another, $nums)) {
$res[] = $k;
$first = $val;
}
}
}
return [];
}
$res = twoSum($nums, $target);
var_dump($res);
运行结果:
array(2) {
[0] =>
int(3)
[1] =>
int(7)
}