題目
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;
}
}