mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加 0015.三数之和.md php版本
This commit is contained in:
@ -354,6 +354,47 @@ def is_valid(strs)
|
||||
end
|
||||
```
|
||||
|
||||
php:
|
||||
|
||||
```php
|
||||
function threeSum(array $nums): array
|
||||
{
|
||||
$result = [];
|
||||
$length = count($nums);
|
||||
if ($length < 3) {
|
||||
return [];
|
||||
}
|
||||
sort($nums);
|
||||
for ($i = 0; $i < $length; $i++) {
|
||||
// 如果大于0结束
|
||||
if ($nums[$i] > 0) break;
|
||||
// 去重
|
||||
if ($i > 0 && $nums[$i] == $nums[$i - 1]) continue;
|
||||
$left = $i + 1;
|
||||
$right = $length - 1;
|
||||
// 比较
|
||||
while ($left < $right) {
|
||||
$sum = $nums[$i] + $nums[$left] + $nums[$right];
|
||||
if ($sum < 0) {
|
||||
$left++;
|
||||
} elseif ($sum > 0) {
|
||||
$right--;
|
||||
} else {
|
||||
array_push($result, [$nums[$i], $nums[$left], $nums[$right]]);
|
||||
while ($left < $right && $nums[$left] == $nums[$left + 1]) $left++;
|
||||
while ($left < $right && $nums[$right - 1] == $nums[$right]) $right--;
|
||||
$left++;
|
||||
$right--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
|
Reference in New Issue
Block a user