题目
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).
思路
这道题跟3Sum那道题(请看本人的上一篇博客)思路类似,先固定一个数,然后用头尾指针从两端向中间靠拢,每次遇到sum更接近target的时候就更新结果,算法的时间复杂度为O(n^2),运行结果击败了9474%的人 : D。
代码
Python
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
leng = len(nums)
if (leng < 3):
return 0
nums.sort()
res = nums[0] + nums[1] + nums[2]
minSub = abs(res - target)
for i in xrange(leng):
if (i > 0 and nums[i-1] == nums[i]):
continue
p = i + 1
q = leng - 1
while (p < q):
tsum = nums[i] + nums[p] + nums[q]
sub = tsum - target
if (sub == 0):
return target
if (abs(sub) < minSub):
#如果和更接近target就更新结果
res = tsum
minSub = abs(sub)
if (sub < 0):
p += 1
else:
q -= 1
return res
Java
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int len = nums.length;
if (nums == null || len < 3) return 0;
//先对数组排序
Arrays.sort(nums);
int i,p,q,sum,sub;
int res = nums[0] + nums[1] + nums[2];
int minSub = Math.abs(res - target);
for (i = 0;i < len;i++){
if (i > 0 && nums[i] == nums[i-1]) continue;
p = i + 1;
q = len - 1;
while (p < q){
sum = nums[i] + nums[p] + nums[q];
sub = sum - target;
if (sub == 0) return target;
//如果有更接近target的,更新结果
if (Math.abs(sub) < minSub){
res = sum;
minSub = Math.abs(sub);
}
if (sub < 0) p++;
else q--;
}
}
return res;
}
}