-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFourSum.php
More file actions
72 lines (55 loc) · 2.14 KB
/
Copy pathFourSum.php
File metadata and controls
72 lines (55 loc) · 2.14 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
/**
* Finds all unique quadruplets in the array which gives the sum of the target.
* @param Integer[] $nums - An array of integers.
* @param Interger $target - The target sum.
* @return Interger[][] - A list of quadruplets that sum up to the target.
*/
class FourSum
{
public function fourSum(array $nums, int $target): array
{
sort($nums);
$result = [];
$n = count($nums);
for($i = 0; $i < $n - 3; $i++) {
// Avoid duplicates
if ($i > 0 && $nums[$i] == $nums[$i - 1]) {
continue;
}
for($j = $i + 1; $j < $n - 2; $j++) {
// Avoid duplicates
if ($j > $i + 1 && $nums[$j] == $nums[$j - 1]) {
continue;
}
$left = $j + 1;
$right = $n - 1;
while($left < $right) {
$sum = $nums[$i] + $nums[$j] + $nums[$left] + $nums[$right];
if ($sum == $target) {
// Found a valid quadruplet
$result[] = [$nums[$i], $nums[$j], $nums[$left], $nums[$right]];
// Skip duplicate values for the third number
while ($left < $right && $nums[$left] == $nums[$left + 1]) {
$left++;
}
// Skip duplicate values for the fourth number
while ($left < $right && $nums[$right] == $nums[$right - 1]) {
$right--;
}
// Move the pointers
$left++;
$right--;
} elseif ($sum < $target) {
// If the sum is less than the target, move the left pointer to the right
$left++;
} else {
// If the sum is greater than the target, move the right pointer to the left
$right--;
}
} // while
} // for $j
} // for $i
return $result;
}
}