1. func abs(num int) int {
    2. if num < 0 {
    3. return -num
    4. }
    5. return num
    6. }
    7. func threeSumClosest(nums []int, target int) int {
    8. result := nums[0] + nums[1] + nums[2]
    9. last_offset := abs(target - result)
    10. sort.Ints(nums)
    11. for i := 0; i < (len(nums) - 2); i++ {
    12. l := i + 1
    13. h := len(nums) - 1
    14. sum := 0
    15. for l < h {
    16. sum = nums[i] + nums[l] + nums[h]
    17. offset := abs(sum - target)
    18. if offset < last_offset {
    19. result = sum
    20. last_offset = offset
    21. }
    22. if sum < target {
    23. l++
    24. } else if sum > target {
    25. h--
    26. } else {
    27. break
    28. }
    29. }
    30. }
    31. return result
    32. }
    33. func main() {
    34. //fmt.Println(threeSumClosest([]int{-1, 2, 1, -4}, 1))
    35. fmt.Println(threeSumClosest([]int{1, 2, 5, 10, 11}, 12))
    36. }