思路:
先任意取三元素和res;记录和目标的差值diff
每次取一个数,在后续列表中找2个元素,满足三数之和最接近target,通过判断三数之和和目标的差值和diff大小,小于diff则将三数之和和差值赋值给res和diff,然后再分析和小于移动左指针,大于移动右指针,直到遍历找到最接近的数
Python:
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) < 3:
return []
nums.sort()
#先任意取三元素和triple;记录和目标的差值diff
res = nums[0] + nums[1] + nums[2]
diff = abs(target - res)
for i in range(0,len(nums)-2):
if nums[i] != nums[i-1] or i == 0:
l = i + 1
r = len(nums) - 1
while l < r:
s = nums[i] + nums[l] + nums[r]
d = abs(target - s) #每次都计算差值
if d < diff:
diff = d
res = s
if s == target:
return target
elif s < target:
l += 1
else:
r -= 1
return res
C++:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3){
return 0;
}
sort(nums.begin(),nums.end());
int res = nums[0] + nums[1] + nums[2];
int diff = abs(target - res);
for (int i = 0; i < nums.size()-2;++i){
if (nums[i] == nums[i-1] && i > 0){
continue;
}
int left = i + 1;
int right = nums.size() - 1;
while(left < right){
int s = nums[i] + nums[left] + nums[right];
int d = abs(target - s);
if (d < diff){
diff = d;
res = s;
}
if(s == target){
return target;
}
else if (s < target){
left ++;
}
else{
right --;
}
}
}
return res;
}
};