这道题和三数之和非常相似,稍微修改一下中间的逻辑就可以直接过了。

    题目:

    1. 给定一个包括 n 个整数的数组 nums 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
    2. 示例:
    3. 输入:nums = [-1,2,1,-4], target = 1
    4. 输出:2
    5. 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2)
    6. 提示:
    7. 3 <= nums.length <= 10^3
    8. -10^3 <= nums[i] <= 10^3
    9. -10^4 <= target <= 10^4

    思路:
    与三数之和一样,先对数组进行排序,接着把三个数中的一个固定,然后双指针移动另外两个数,不断的向target靠近,最后就能得出答案;当然,中间也要考虑去重,这里的去重主要是考虑到执行时间,理论上不进行去重对最终结果也没有影响。

    1. /*
    2. * @lc app=leetcode.cn id=16 lang=golang
    3. *
    4. * [16] 最接近的三数之和
    5. */
    6. // @lc code=start
    7. func threeSumClosest(nums []int, target int) int {
    8. var index int
    9. n := len(nums)
    10. minDiff := math.MaxInt32
    11. quickSort(nums) //先进行排序,固定一个值
    12. // fmt.Println(nums)
    13. update := func(cur int) {
    14. if abs(cur-target) < abs(minDiff-target) {
    15. minDiff = cur
    16. }
    17. }
    18. for index = 0; index < n; index++ { //这里要从0开始,与三数之和不同
    19. // head, tail := 0, len(nums)-1 //每次都从0到length-1
    20. if index > 0 && nums[index] == nums[index-1] {
    21. continue
    22. }
    23. left, right := index+1, n-1
    24. for left < right {
    25. sum := nums[index] + nums[left] + nums[right]
    26. if sum == target {
    27. return target
    28. }
    29. update(sum)
    30. if left > index+1 && left < n && nums[left] == nums[left-1] {
    31. left++
    32. continue
    33. }
    34. if right < n-1 && right > left && nums[right] == nums[right+1] {
    35. right--
    36. continue
    37. }
    38. if sum > target {
    39. right--
    40. } else {
    41. left++
    42. }
    43. }
    44. }
    45. return minDiff
    46. }
    47. func quickSort(nums []int) {
    48. if len(nums) < 2 {
    49. return
    50. }
    51. head, tail := 0, len(nums)-1
    52. reference := nums[0]
    53. i := 1
    54. for head < tail {
    55. if nums[i] < reference {
    56. nums[i], nums[head] = nums[head], nums[i]
    57. i++
    58. head++
    59. } else {
    60. nums[i], nums[tail] = nums[tail], nums[i]
    61. tail--
    62. }
    63. }
    64. quickSort(nums[:head])
    65. quickSort(nums[head+1:])
    66. }
    67. func abs(x int) int {
    68. switch {
    69. case x == 0:
    70. return 0
    71. case x < 0:
    72. return -1 * x
    73. }
    74. return x
    75. }
    76. // @lc code=end