0016.3 Sum Closest

# 16. 3Sum Closest#

## 题目 #

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.

Example:

``````
Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

``````

## 代码 #

``````
package leetcode

import (
"math"
"sort"
)

// 解法一 O(n^2)
func threeSumClosest(nums []int, target int) int {
n, res, diff := 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]
if abs(sum-target) < diff {
res, diff = sum, abs(sum-target)
}
if sum == target {
return res
} else if sum > target {
k--
} else {
j++
}
}
}
}
return res
}

// 解法二 暴力解法 O(n^3)
func threeSumClosest1(nums []int, target int) int {
res, difference := 0, math.MaxInt16
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
for k := j + 1; k < len(nums); k++ {
if abs(nums[i]+nums[j]+nums[k]-target) < difference {
difference = abs(nums[i] + nums[j] + nums[k] - target)
res = nums[i] + nums[j] + nums[k]
}
}
}
}
return res
}

func abs(a int) int {
if a > 0 {
return a
}
return -a
}

``````

Sep 6, 2020