Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit868c18e

Browse files
Merge pull requestyoungyangyang04#455 from amdrose/master
添加 0001.两数之和.md php版本 和 添加 0015.三数之和.md php版本
2 parentsf04f4e7 +46a4b51 commit868c18e

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

‎problems/0001.两数之和.md

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,23 @@ var twoSum = function (nums, target) {
187187
};
188188
```
189189

190-
190+
php
191+
192+
```php
193+
function twoSum(array $nums, int $target): array
194+
{
195+
for ($i = 0; $i < count($nums);$i++) {
196+
// 计算剩下的数
197+
$residue = $target - $nums[$i];
198+
// 匹配的index,有则返回index, 无则返回false
199+
$match_index = array_search($residue, $nums);
200+
if ($match_index !== false && $match_index != $i) {
201+
return array($i, $match_index);
202+
}
203+
}
204+
return [];
205+
}
206+
```
191207

192208

193209
-----------------------

‎problems/0015.三数之和.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,47 @@ def is_valid(strs)
354354
end
355355
```
356356

357+
php:
358+
359+
```php
360+
function threeSum(array $nums): array
361+
{
362+
$result = [];
363+
$length = count($nums);
364+
if ($length < 3) {
365+
return [];
366+
}
367+
sort($nums);
368+
for ($i = 0; $i < $length; $i++) {
369+
// 如果大于0结束
370+
if ($nums[$i] > 0) break;
371+
// 去重
372+
if ($i > 0 && $nums[$i] == $nums[$i - 1]) continue;
373+
$left = $i + 1;
374+
$right = $length - 1;
375+
// 比较
376+
while ($left < $right) {
377+
$sum = $nums[$i] + $nums[$left] + $nums[$right];
378+
if ($sum < 0) {
379+
$left++;
380+
} elseif ($sum > 0) {
381+
$right--;
382+
} else {
383+
array_push($result, [$nums[$i], $nums[$left], $nums[$right]]);
384+
while ($left < $right && $nums[$left] == $nums[$left + 1]) $left++;
385+
while ($left < $right && $nums[$right - 1] == $nums[$right]) $right--;
386+
$left++;
387+
$right--;
388+
}
389+
}
390+
}
391+
392+
return $result;
393+
}
394+
```
395+
396+
397+
357398
-----------------------
358399
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
359400
* B站视频:[代码随想录](https://space.bilibili.com/525438321)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp