固定左边数值,左右指针网中间赶
原创
©著作权归作者所有:来自51CTO博客作者wx596330ff6d68f的原创作品,请联系作者获取转载授权,否则将追究法律责任
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());//将nums里面的元素从小到大排序
int preSum,left,right,sum;
bool First = true;
for (int i = 0; i < nums.size(); i++)
{
left = i + 1; right = nums.size() - 1;
while (left < right)
{
sum = nums[i] + nums[left] + nums[right];
if (First) {//第一次将preSum初始化
preSum = sum;
First = false;
}
else {
if (abs(target - sum) < abs(target - preSum)) {
preSum = sum;
}
}
if (preSum == target) { return preSum; }
if (sum > target) { right--; }
else { left++; }
}
}
return preSum;
}
};