From ddf0530d44bf1e35322dbeb80e61c26134d0c014 Mon Sep 17 00:00:00 2001 From: whosphp <11045186+whosphp@users.noreply.github.com> Date: Thu, 4 Aug 2022 14:08:38 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=200001.=E4=B8=A4=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C=20php=E7=89=88=E6=9C=AC=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) 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 [];