From 3e1d341aea97d6f162606827b3e55151820fc299 Mon Sep 17 00:00:00 2001 From: nolanzzz Date: Thu, 2 Sep 2021 23:54:21 -0400 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200018.=E5=9B=9B=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/0018.四数之和.md | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 6af033b9..c81c5df7 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -310,6 +310,49 @@ var fourSum = function(nums, target) { }; ``` +PHP: +```php +class Solution { + /** + * @param Integer[] $nums + * @param Integer $target + * @return Integer[][] + */ + function fourSum($nums, $target) { + $res = []; + sort($nums); + for ($i = 0; $i < count($nums); $i++) { + if ($i > 0 && $nums[$i] == $nums[$i - 1]) { + continue; + } + for ($j = $i + 1; $j < count($nums); $j++) { + if ($j > $i + 1 && $nums[$j] == $nums[$j - 1]) { + continue; + } + $left = $j + 1; + $right = count($nums) - 1; + while ($left < $right) { + $sum = $nums[$i] + $nums[$j] + $nums[$left] + $nums[$right]; + if ($sum < $target) { + $left++; + } + else if ($sum > $target) { + $right--; + } + else { + $res[] = [$nums[$i], $nums[$j], $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; + } +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)