给定 nums = [2, 7, 11, 15], target = 9,因为 nums[0] + nums[1] = 2 + 7 = 9,所以返回 [0, 1]
php
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum($nums, $target) {
$scan = [];
foreach($nums as $k => $v){
$diff = $target - $v;
if($k == 0){
$scan[$v]=$k;
continue;
}
if(isset($scan[$diff])){
return [$scan[$diff],$k];
}
$scan[$v]=$k;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。