题目
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解法
和题目和3Sum很像,不过不再是求三个数的和是否为0,而是三个数的和与target的最小差,因此需要记录当前最优解并不断更新其值。
该方法时间复杂度为:O(N^2)
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int closest = 0;
int diff = INT_MAX;
if (nums.size() < 3)
return closest;
sort(nums.begin(),nums.end());
for (int i = 0; i < nums.size() - 2; i++) {
while(i > 0 && i < nums.size() && nums[i] == nums[i-1])
i++;
int start = i + 1, end = nums.size() - 1;
while (start < end) {
int sum = nums[i] + nums[start] + nums[end];
if (sum == target) {
return sum;
} else if (sum < target) {
if (target - sum < diff) {
diff = target - sum;
closest = sum;
}
start++;
while(start < end && nums[start] == nums[start-1])
start++;
} else {
if (sum - target < diff) {
diff = sum - target;
closest = sum;
}
end--;
while(start < end && nums[end] == nums[end + 1])
end--;
}
}
}
return closest;
}
};