LeetCode 16. 3Sum Closest

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 + 1end = n - 1
如果当前sum等于target,则begin++end--
如果当前sum大于target,则end--
如果当前sum小于target,则begin++
然后每次根据sum与target的差值更新result。
注意,result为long类型,避免一开始是INT_MAX最大值,int类型减去一个负数后造成溢出错误。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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;
}
};
------本文结束感谢阅读------