-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.php
35 lines (35 loc) · 1001 Bytes
/
Solution.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
/**
* @param Integer[] $nums
* @return Integer[][]
*/
function threeSum($nums) {
sort($nums);
$ans = [];
$n = count($nums);
for ($i = 0; $i < $n - 2 && $nums[$i] <= 0; ++$i) {
if ($i > 0 && $nums[$i] == $nums[$i - 1]) {
continue;
}
$j = $i + 1;
$k = $n - 1;
while ($j < $k) {
$x = $nums[$i] + $nums[$j] + $nums[$k];
if ($x < 0) {
++$j;
} elseif ($x > 0) {
--$k;
} else {
$ans[] = [$nums[$i], $nums[$j++], $nums[$k--]];
while ($j < $k && $nums[$j] == $nums[$j - 1]) {
++$j;
}
while ($j < $k && $nums[$k] == $nums[$k + 1]) {
--$k;
}
}
}
}
return $ans;
}
}