mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -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 [];
|
||||
|
Reference in New Issue
Block a user