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).
题解: 首先将数组排序,固定一个数字, 设定两个指针,当这3个数的和大于target的时候,第二个指针往前移动,当小于target的时候,第一个指针往后移动,知道两个指针指向相同的值或者是三个数的和等于target。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int closest = nums[0] + nums[1] + nums[2];
unsigned int diff = abs(target - closest);
sort(nums.begin(), nums.end());
int length = nums.size();
for (int i = 0; i < length - 2; ++i)
{
int j = i + 1;
int k = length - 1;
while (j != k && diff != 0)
{
int tempSum = nums[i] + nums[j] + nums[k];
unsigned int tempDiff = abs(target - tempSum);
if (tempDiff < diff)
{
diff = tempDiff;
closest = tempSum;
}
if (tempSum > target)
{
--k; //前移第二个指针
}
if (tempSum < target)
{
++j; //后移第一个指针
}
}
if (diff == 0)
break;
}
return closest;
}
};