难度:medium
描述:
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).
思路:
大概就是让你找给出的数中的三个,使得这三个的和同目标最接近。
这个可以用穷举来暴力破解,找出三个数的所有组合。
但是毫无疑问像3Sum那道题一样,效率不高,所以可以借鉴3sum的方法,先排序,然后通过固定一个数,让他退化成2sum后用头尾指针逼近的方法来解决。
不过这次不需要严格相等了,而是需要找出和目标最接近的,但是我们依然可以用相同的方法来逼近,只要用变量记住最靠近目标的值就行。
代码:
#include <algorithm>
class Solution {
public:
int abs(int i){
if (i < 0) return -i;
else return i;
}
int threeSumClosest(vector<int>& num, int target) {
vector<int> nums = num;
int result = 99999999;
int min = 99999999; //minimum gap
sort(nums.begin(),nums.end());
for (int i = 0; i < nums.size(); i++){
int begin = i+1;
int end = nums.size()-1;
while (begin < end){
int sum = nums[begin]+nums[end]+nums[i];
int minus = sum-target;
int gap = abs(minus);
if (gap == 0){
return sum;
} else if (minus > 0){
if (gap < min) { // if get closer to target, update the result!
min = gap;
result = sum;
}
end--;
} else {
if (gap < min) {
min = gap;
result = sum;
}
begin++;
}
}
}
return result;
}
};