Description
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).
分析
- 这道题对一开始上手的人来说,可能思维不难,但是代码写好的话,就有点困难,比如在寻找之前先从小到大排序,用diff来记录目标和最近的差值,然后遍历寻找。
- for(){
while(left<right){
}
}
这种模式在leetcode的其他几个题中会遇见,这可以作为这一类题目的通用解法。 - 解法有点暴力
C++ 代码
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int closet=nums[0]+nums[1]+nums[2];
int diff=abs(closet-target);
for(int i=0;i<nums.size()-2;i++){
int left=i+1;
int right=nums.size()-1;
while(left<right){
int sum=nums[i]+nums[left]+nums[right];
if(diff>abs(sum-target)){
diff=abs(sum-target);
closet=sum;
}
if(sum<target){
left++;
}else{
right--;
}
}
}
return closet;
}
};
Python 代码
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
res = 2**31
for i in range(len(nums)):
if i>0 and nums[i]==nums[i-1]:
continue
left = i+1
right = len(nums)-1
while left<right:
val = nums[i]+nums[left]+nums[right]
if abs(val-target)<abs(res-target):
res = val
if val>target:
right-=1
elif val<target:
left+=1
else:
return target
return res