原题:
Given an array
nums
of n integers and an integertarget
, find three integers innums
such that the sum is closest totarget
. 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).
类似3sum,但是要找到的是最接近的,由3sum得来的灵感,详情可以看https://blog.csdn.net/cyr429/article/details/102573128,结果:
Success
Runtime: 8 ms, faster than 80.35% of C++ online submissions for 3Sum Closest.
Memory Usage: 8.5 MB, less than 100.00% of C++ online submissions for 3Sum Closest.
代码:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int l=0;
int r=0;
int min=nums[0]+nums[1]+nums[2];
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size()-2;i++){
if(i > 0 && nums[i]==nums[i-1]){continue;}
int l=i+1;
int r=nums.size()-1;
while(l<r){
int sum=nums[i]+nums[l]+nums[r];
if(abs(sum-target)<abs(min-target)){min=sum;}
if(sum<target){l++;}
else{r--;}
}
}
return min;
}
};