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:
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;
}
};