每日算法——leetcode系列
问题 3Sum Closest
Difficulty: 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.
<pre>
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).
</pre>
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
}
};
翻译
三数和
难度系数:中等
给定一个有n个整数的数组S, 找出数组S中三个数的和最接近一个指定的数。 返回这三个数的和。 你可以假定每个输入都有一个结果。
思路
思路跟3Sum很像, 不同的就是不用去重复, 要记录三和最接近target的和值。
代码
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result = 0;
int minDiff = INT32_MAX;
// 排序
sort(nums.begin(), nums.end());
int n = static_cast<int>(nums.size());
for (int i = 0; i < n - 2; ++i) {
int j = i + 1;
int k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
int diff = abs(sum - target);
// 记录三和最接近target的和值
if (minDiff > diff){
result = sum;
minDiff = diff;
}
else if (sum < target){
j++;
}
else if (sum > target){
k--;
}
else{
return result;
}
}
}
return result;
}
};