题意
给一个数组和一个target,要求在数组中找三个数a, b, c,使a + b + c更接近于target。
思路
和3Sum类似,转化为2Sum处理。
先排序,然后枚举a,那么就转化成了b + c更接近于x = target - a。
然后从a的位置之后,设置两个指针j和k指向首和尾,然后按照一定规则往中间走(用z记录距离target的绝对值):
- b+c<x:更新z,并且j后挪一位。
- b+c>x:更新z,并且k前挪一位。
- 直接返回targt。
代码
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size(), absans = INT_MAX;
bool f = true; //f: positive, flase: negative
sort(nums.begin(), nums.end());
for (int i = 0; i < n; i++) {
int x = target - nums[i];
int j = i + 1, k = n - 1;
while (j < k) {
if (nums[j] + nums[k] == x) return target;
if (nums[j] + nums[k] < x) {
if (x - (nums[j] + nums[k]) < absans) {
absans = x - (nums[j] + nums[k]);
f = false;
}
j++;
} else {
if (nums[j] + nums[k] - x < absans) {
absans = nums[j] + nums[k] - x;
f = true;
}
k--;
}
}
while (nums[i] == nums[i + 1] && i + 1 < n) i++;
}
return target + (f ? absans : -absans);
}
};

634

被折叠的 条评论
为什么被折叠?



