题目:https://leetcode-cn.com/problems/3sum-closest/ 代码:class Solution { public: int threeSumClosest(vector& nums, int target) {
sort(nums.begin(), nums.end()); int size = nums.size(); //if (nums.front() > target) return nums[0] + nums[1] + nums[2]; //if (nums.back() < target) return nums[size - 1] + nums[size - 2] + nums[size - 3]; int res = nums[0] + nums[2] + nums[1]; for (int i = 0; i < nums.size(); i++) { int a = nums[i]; //if (a > target) break; int l = i + 1; int r = nums.size() - 1; if(l >=r) break; int tmp = nums[l] + nums[r] + a; while (l < r) { int sum = nums[l] + nums[r] + a; if ( abs(sum - target) < abs(tmp - target)) { tmp = sum; } if (nums[l] + nums[r] == target -a) { tmp = target; return target; } else if (nums[l] + nums[r] >target -a) { r--; } else { l++; } } if (abs(res - target)> abs(tmp - target)) res = tmp; } return res;}
};
结果: