10 3SumClosest
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) {
int sum = 0;
int d_min = INT_MAX;
int len = nums.size();
for(int i = 0;i < len; i++ )
{
for(int j = i + 1 ;j< len; j++)
{
for( int k = j+1; k<len; k++)
{
int temp = nums[i] + nums[j] + nums[k];
int d = abs(temp - target);
if(d < d_min)
{
d_min = d;
sum = temp;
}
else;
}
}
}
return sum;
}
};
比较快速的方法是使用 排序 + 两头逼近法, 下面算法用时约8ms
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int len = nums.size();
sort(nums.begin(), nums.end());
int min = nums[0]+nums[1]+nums[2];
int max = nums[len-1]+nums[len-2]+nums[len-3];
if(target < min) return min;
if(target > max) return max;
//from two side -> center
int left,right;
int d_min = INT_MAX;
int sum = 0;
for(int i=0;i<len;i++)
{
left = i+1;
right = len -1 ;
while(left<right)
{
int temp = nums[i] + nums[left] + nums[right];
int d_curr = abs(temp - target);
if(d_curr < d_min)
{
d_min = d_curr;
sum = temp;
}
if(temp < target) left++;
else if(temp == target) return target;
else right--;
}
}
return sum;
}
};