diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index a15e1349..5bedd0a0 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -263,13 +263,15 @@ php ```php function twoSum(array $nums, int $target): array { - for ($i = 0; $i < count($nums);$i++) { - // 计算剩下的数 - $residue = $target - $nums[$i]; - // 匹配的index,有则返回index, 无则返回false - $match_index = array_search($residue, $nums); - if ($match_index !== false && $match_index != $i) { - return array($i, $match_index); + $map = []; + foreach($nums as $i => $num) { + if (isset($map[$target - $num])) { + return [ + $i, + $map[$target - $num] + ]; + } else { + $map[$num] = $i; } } return [];