December 17, 2019
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
}
直接三层循环进行计算、比较就可以了。
痕迹
没有过去,就没法认定现在的自己