Description:
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).
思路:與3Sum思想一致
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
long res = INT_MAX;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); i ++) {
int left = i+1, right = nums.size()-1;
while(left < right) {
int sum = nums[i] + nums[left] + nums[right];
if(sum == target)
return target;
else if(sum > target)
right --;
else
left ++;
if(abs(sum-target) < abs(res-target))
res = sum;
}
}
return (int)res;
}
};