title | date |
---|---|
16. 最接近的三数之和 |
2019-12-17T21:49:00.000Z |
https://leetcode-cn.com/problems/3sum-closest/
使用语言:Go
func threeSumClosest(nums []int, target int) int {
var res *int
for i, n1 := range nums[:len(nums) - 2] {
for j, n2 := range nums[i+1:len(nums) - 1] {
for _, n3 := range nums[i+j+2:len(nums)] {
sum := n1 + n2 + n3
if sum == target {
return sum
}
if res == nil {
res = &sum
continue
}
sumDistance := sum - target
resDistance := *res - target
if sumDistance < 0 {
sumDistance = -sumDistance
}
if resDistance < 0 {
resDistance = -resDistance
}
if sumDistance < resDistance {
res = &sum
}
}
}
}
return *res
}
直接三层循环进行计算、比较就可以了。