题意:

image.png

解题思路:

  1. 思路:
  2. 1. 首先对 nums 进行从小到大排序;
  3. 2. 枚举第一组数字当成后面比较的值,然后采用两头夹逼的方式,无重复的寻找下一组值;
  4. 3. 依次迭代计算每一组值,更新最接近目标的值;

PHP代码实现:

  1. class Solution {
  2. function threeSumClosest($nums, $target) {
  3. if (!$nums) return [];
  4. sort($nums);
  5. $min = $nums[0] + $nums[1] + $nums[2];
  6. for ($i = 0; $i < count($nums) - 2; $i++) {
  7. $left = $i + 1;
  8. $right = count($nums) - 1;
  9. while ($left < $right) {
  10. $sum = $nums[$i] + $nums[$left] + $nums[$right];
  11. if ($sum > $target) {
  12. $right--;
  13. } else $left ++;
  14. if (abs($sum - $target) < abs($min - $target)) {
  15. $min = $sum;
  16. }
  17. }
  18. }
  19. return $min;
  20. }
  21. }

GO代码实现:

  1. func threeSumClosest(nums []int, target int) int {
  2. min := nums[0] + nums[1] + nums[2]
  3. sort.Ints(nums)
  4. for i := 0; i < len(nums) - 2; i++ {
  5. left, right := i + 1, len(nums) - 1
  6. for left < right {
  7. sum := nums[i] + nums[left] + nums[right]
  8. if sum > target {
  9. right--
  10. } else {
  11. left++
  12. }
  13. if (abs(sum, target) < abs(min, target)) {
  14. min = sum
  15. }
  16. }
  17. }
  18. return min
  19. }
  20. func abs(a, b int) int {
  21. if a < b {
  22. return b - a
  23. }
  24. return a - b
  25. }