题目描述
给出含有n个整数的数组s,找出s中和加起来的和最接近给定的目标值的三个整数。返回这三个整数的和。你可以假设每个输入都只有唯一解。
例如,给定的整数 S = {-1 2 1 -4}, 目标值 = 1.↵↵ 最接近目标值的和为 2. (-1 + 2 + 1 = 2).
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).
示例1
输出
复制0 链接:https://www.nowcoder.com/questionTerminal/291a866d7c904563876b373b0b157dde?f=discussion
来源:牛客网
class
Solution {
public
:
int
threeSumClosest(vector<
int
> &num,
int
target) {
int
n = num.size();
int
result = num[0] + num[1] + num[n-1];
sort(num.begin(),num.end());
for
(
int
i=0;i<n-2;i++)
{
int
start = i + 1;
int
end = n - 1;
while
(start < end)
{
int
sum = num[i] + num[start] + num[end];
if
(sum < target)
start++;
else
end--;
if
(
abs
(sum-target) <
abs
(result-target))
result = sum;
}
}
return
result;
}
};