题目:
3Sum Closest
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.
For 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).
Solution:
解法就是上一题思路的延伸。
1、先排序
2、求和,与target比较
3、找出相距最小的和
int threeSumClosest(vector<int>& nums, int target)
{
int i,j,k;
int n = nums.size();
if(n<3)
return 0;
int min_value = abs(nums[0]+nums[1]+nums[2] - target);
int result = nums[0]+nums[1]+nums[2];
QuickSort(nums,0,n-1);
for(i=0;i<n;i++)
{
int current_num = nums[i];
j = i+1;
k = n-1;
while(j<k)
{
int sum = nums[j] + nums[k] + current_num;
if(sum - target < 0)
{
j++;
}
else if(sum - target > 0)
{
k--;
}
else
{
result = sum;
return result;
}
if(abs(sum-target) < min_value)
{
min_value = abs(sum-target);
result = sum;
}
}
}
return result;
}
void QuickSort(vector<int>& nums,int low,int high)
{
if(low<high)
{
int pivot = nums[low];
int first = low;
int last = high;
while(first<last)
{
while(nums[last] >= pivot && first <last)
{
last--;
}
nums[first] = nums[last];
while(nums[first] < pivot && first <last)
{
first++;
}
nums[last] = nums[first];
}
nums[first] = pivot;
QuickSort(nums,low,first-1);
QuickSort(nums,first+1,high);
}
else
return;
}