Skip to content

Latest commit

 

History

History
43 lines (38 loc) · 1.57 KB

16.md

File metadata and controls

43 lines (38 loc) · 1.57 KB
title date
16. 最接近的三数之和
2019-12-17T21:49:00.000Z

https://leetcode-cn.com/problems/3sum-closest/

使用语言:Go

func threeSumClosest(nums []inttarget intint {
    var res *int
    for in1 := range nums[:len(nums- 2] {
        for jn2 := 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
}

直接三层循环进行计算、比较就可以了。