mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 21:50:49 +08:00
添加 0018.四数之和 PHP版本
This commit is contained in:
@ -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)
|
||||
|
Reference in New Issue
Block a user