题⽬
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
给定⼀个数组,要求在这个数组中找出 3 个数之和离 target 最
夹逼算法
package main
import (
"fmt"
"leetCode/utils" // utils.Abs()取绝对值
"math"
"sort"
)
// 解法⼀ O(n^2)
func threeSumClosest(nums []int, target int) int {
n, res, distance := len(nums), 0, math.MaxInt32
if n > 2 {
sort.Ints(nums)//从小到大排序
for i := 0; i < n-2; i++ {
for j, k := i+1, n-1; j < k; {
sum := nums[i] + nums[j] + nums[k]//此时sum最大
if utils.Abs(sum-target) < distance {//若距离减少
res, distance = sum, utils.Abs(sum-target)
}
if sum == target {
return res
} else if sum > target {
k--
} else {
j++
}
}
}
}
return res
}
func main() {
a := []int{-4,-4,-1,-1,0,1,2,2}
fmt.Println()
fmt.Println(threeSumClosest(a, 8))
}