Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
tag:
java
public int threeSumClosest(int[] nums, int target) {
int closest = nums[0]+nums[1]+nums[nums.length-1];
Arrays.sort(nums);
for(int i=0; i<nums.length; i++) {
int l = i+1, r = nums.length-1;
while(l<r) {
int sum = nums[i]+nums[l]+nums[r];
if(sum==target) return sum;
else if(sum<target) l++;
else r--;
closest = Math.abs(sum-target)<Math.abs(closest-target) ? sum : closest;
}
}
return closest;
}
go
func threeSumclosest(nums []int, target int) int {
len := len(nums)
close := nums[0] + nums[1] + nums[len-1]
sort.Ints(nums)
for i := 0; i < len; i++ {
for p, q := i+1, len-1; p < q; {
sum := nums[i] + nums[p] + nums[q]
if sum == target {
return sum
} else if sum < target {
p++
} else {
q--
}
if math.Abs(float64(sum-target)) < math.Abs(float64(close-target)) {
close = sum
}
}
}
return close
}