mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 04:54:51 +08:00
添加 0015.三数之和 PHP版本
This commit is contained in:
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user