最接近的三数之和 3sum-closet
题目描述
给出含有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).
示例
输入
[0,0,0],1
输出
0
解题思路
- 先排序,用三指针
- index指针用于遍历数组,初始为0,范围为0~n - 3(留出两个位置)
- left和right指针用于每次index遍历时的双指针收缩,初始分别为index + 1和n - 1
- temp = num[index] + num[left] + num[right]
- 如果temp < target,则left ++
- 如果temp >=target,则right - -
- 如果abs(temp - target) < abs(res - target),则更新res
class Solution {
public:
int threeSumClosest(vector<int>& num, int target) {
int n = num.size();
//先将原数组排序
sort(num.begin(), num.end());
//用于保存和目标值最接近的三数之和
int res = num[0] + num[1] + num[n - 1];
for(int index = 0; index < n - 2; index ++) {
int left(index + 1), right(n - 1);
while(left < right) {
int temp = num[index] + num[left] + num[right];
//如果三数之和小于目标值,就左指针加一,否则右指针减一
temp < target ? left ++ : right --;
//当三数之和与目标值相差最小时,更新res
if(abs(temp - target) < abs(res - target)) {
res = temp;
}
}
}
return res;
}
};