forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.php
39 lines (32 loc) · 954 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
36
37
38
39
class Solution {
/**
* @param int[] $nums
* @param int $target
* @return int
*/
function threeSumClosest($nums, $target) {
$n = count($nums);
$closestSum = $nums[0] + $nums[1] + $nums[2];
$minDiff = abs($closestSum - $target);
sort($nums);
for ($i = 0; $i < $n - 2; $i++) {
$left = $i + 1;
$right = $n - 1;
while ($left < $right) {
$sum = $nums[$i] + $nums[$left] + $nums[$right];
$diff = abs($sum - $target);
if ($diff < $minDiff) {
$minDiff = $diff;
$closestSum = $sum;
} elseif ($sum < $target) {
$left++;
} elseif ($sum > $target) {
$right--;
} else {
return $sum;
}
}
}
return $closestSum;
}
}