Leetcode 16 最接近的三数之和
题目描述
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
来源:力扣(LeetCode)题目链接
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解1(暴力双指针)
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int s_nums = nums.size();
int best = 0x7FFF;
//匿名函数[捕获列表](参数列表)->返回类型{函数体}
auto change = [&best,target](int cur_val){
if(abs(best-target) > abs(cur_val-target))
best = cur_val;
};
for(int i = 0; i < s_nums-2; i++){
int sum = best;
int left = i+1;
int right = s_nums-1;
while(left < right){
sum = nums[i]+nums[left]+nums[right];
if(sum > target)
right--;
else if(sum < target)
left++;
else{
left++;
right--;
}
change(sum);
}
}
return best;
}
};