LeetCode 16. 3Sum Closest
Description:
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.
Example:
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).
分析:
首先对数组nums排序,确定第一个数为nums[i],设定变量
begin = i + 1
,end = n - 1
;
如果当前sum等于target,则begin++
,end--
;
如果当前sum大于target,则end--
;
如果当前sum小于target,则begin++
;
然后每次根据sum与target的差值更新result。
注意,result为long类型,避免一开始是INT_MAX
最大值,int类型减去一个负数后造成溢出错误。
代码如下:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
long result = INT_MAX;
int n = nums.size();
sort(nums.begin(), nums.end());
for (int i = 0; i < n; i++) {
int begin = i + 1, end = n - 1;
while (begin < end) {
int sum = nums[i] + nums[begin] + nums[end];
if (sum == target) {
begin++;
end--;
}
else if (sum > target) {
end--;
}
else {
begin++;
}
if (abs(sum - target) < abs(result - target)) {
result = sum;
}
}
}
return (int)result;
}
};