LeetCode OJ-16.3Sum Closest(最接近三数和)
题目描述
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).
Subscribe to see which companies asked this question
题目理解
与三数和问题有点类似,但这题更加容易,不要求去重,并假设结果唯一。代码可以借鉴三数和问题,在’>’,’<’两种情况时,判断三数相加的和与target在坐标轴上的距离是否更小即可,并记录这个更小的值。具体代码如下:
Code
int three_nums_closest(vector<int> &nums_vec, int target)
{
int res = INT_MAX;
sort(nums_vec.begin(), nums_vec.end(), cmp); //与三数和一样,排序处理
int i, j, k;
int sz = (int) nums_vec.size();
int dis = res;
int sum;
for (i = 0; i < sz - 2; ++i) {
j = i + 1;
k = sz - 1;
while (j < k) {
sum = nums_vec[i] + nums_vec[j] + nums_vec[k];
if (sum > target) {
if (abs(target - sum) < dis) { //target与sum坐标轴上的距离小于dis
//说明更接近
dis = abs(target - sum);
res = sum;
}
--k; //与三数和问题一样,大于目标值,也要将较大的迭代器前移
}
else if (sum < target) {
if (abs(target - sum) < dis) {
dis = abs(target - sum);
res = sum;
}
++j; //与三数和问题一样,小于目标值,也要将较小的迭代器后移
}
else {
res = sum;
return res; //相等情况,说明距离为0,直接返回结果,题目说明了结果唯一
}
}
}
return res;
}
int cmp(int __x, int __y)
{
return __x < __y;
}