From e6975415370067128b8a625944fedec91728f4fc Mon Sep 17 00:00:00 2001 From: nolanzzz Date: Thu, 2 Sep 2021 23:53:36 -0400 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200015.=E4=B8=89=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C=20PHP=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 1adb2d24..adb9a113 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -393,6 +393,46 @@ function threeSum(array $nums): array } ``` +PHP: +```php +class Solution { + /** + * @param Integer[] $nums + * @return Integer[][] + */ + function threeSum($nums) { + $res = []; + sort($nums); + for ($i = 0; $i < count($nums); $i++) { + if ($nums[$i] > 0) { + return $res; + } + if ($i > 0 && $nums[$i] == $nums[$i - 1]) { + continue; + } + $left = $i + 1; + $right = count($nums) - 1; + while ($left < $right) { + $sum = $nums[$i] + $nums[$left] + $nums[$right]; + if ($sum < 0) { + $left++; + } + else if ($sum > 0) { + $right--; + } + else { + $res[] = [$nums[$i], $nums[$left], $nums[$right]]; + while ($left < $right && $nums[$left] == $nums[$left + 1]) $left++; + while ($left < $right && $nums[$right] == $nums[$right - 1]) $right--; + $left++; + $right--; + } + } + } + return $res; + } +} +``` -----------------------