16、3Sum Closest
最接近的三數之和
給一個包含 n 個整數的數組 S, 找到和與給定整數 target 最接近的三元組,返回這三個數的和。
注意事項
只需要返回三元組之和,無需返回三元組本身
樣例
例如 S = [-1,
2, 1, -4]
and target = 1
. 和最接近 1 的三元組是 -1 + 2 + 1 = 2.
代碼:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int N=nums.size();
sort(nums.begin(), nums.end());
int res=nums[0]+nums[1]+nums[2];
for(int i=0;i<N-2;i++)
{
int left=i+1,right=N-1;
while(left<right)
{
int sum=nums[i]+nums[left]+nums[right];
if(abs(sum-target)<abs(res-target)) res=sum;
else if(sum<target)left++;
else right--;
if(res==target)return res;
}
}
return res;
}
};