每日leetcode(35)
16. 最接近的三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
这和三数之和接近
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int low, high;
int numSize = nums.size();
int vecSize = numSize - 2;
int res,sum;
if (numSize <= 3) return accumulate(nums.begin(), nums.end(), 0);
sort(nums.begin(), nums.end());
res = nums[0] + nums[1] + nums[2];
for (int i = 0; i < vecSize; i++) {
low = i + 1;
high = numSize - 1;
cout << low << " " << high << "\n";
while (low < high) {
sum = nums[i] + nums[low] + nums[high] - target;
cout << "sum:" << sum << "\n";
if (abs(sum) < abs(res-target)) res = nums[i] + nums[low] + nums[high];
cout << "res:" << res << "\n";
if (sum < 0) while(low<high && nums[low]==nums[++low]);
else if (sum > 0) while(low<high && nums[high]==nums[--high]);
else return res;
}
}
return res;
}
};