题意:
解题思路:
思路:
1. 首先对 nums 进行从小到大排序;
2. 枚举第一组数字当成后面比较的值,然后采用两头夹逼的方式,无重复的寻找下一组值;
3. 依次迭代计算每一组值,更新最接近目标的值;
PHP代码实现:
class Solution {
function threeSumClosest($nums, $target) {
if (!$nums) return [];
sort($nums);
$min = $nums[0] + $nums[1] + $nums[2];
for ($i = 0; $i < count($nums) - 2; $i++) {
$left = $i + 1;
$right = count($nums) - 1;
while ($left < $right) {
$sum = $nums[$i] + $nums[$left] + $nums[$right];
if ($sum > $target) {
$right--;
} else $left ++;
if (abs($sum - $target) < abs($min - $target)) {
$min = $sum;
}
}
}
return $min;
}
}
GO代码实现:
func threeSumClosest(nums []int, target int) int {
min := nums[0] + nums[1] + nums[2]
sort.Ints(nums)
for i := 0; i < len(nums) - 2; i++ {
left, right := i + 1, len(nums) - 1
for left < right {
sum := nums[i] + nums[left] + nums[right]
if sum > target {
right--
} else {
left++
}
if (abs(sum, target) < abs(min, target)) {
min = sum
}
}
}
return min
}
func abs(a, b int) int {
if a < b {
return b - a
}
return a - b
}