LeetCode16----------3Sum Closest
意思是求三数相加最接近target的一个结果,也就是加起来与target相减绝对值最小的。这次是要求返回三数之和,而不是这个三个数组成的三元组。
最开始想到的就是套用上一题的思路。
不过试了试三重循环直接就过了,也就算了,后来网上查了一下,有用15题相似代码解决的。
代码:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int numLen = nums.size();
int i;
int j;
int k;
int closest;
int result;
int minAbs=INT_MAX;
cout << endl;
for(i=0;i<numLen-2;i++)
{
for(j=i+1;j<numLen-1;j++)
{
for(k=j+1;k<numLen;k++)
{
closest = nums[i]+nums[j]+nums[k];
if(closest == target )
return closest;
else if(closest > target)
{
if(closest - target < minAbs)
{
minAbs=closest - target;
result = closest;
}
}
else
{
if(target - closest < minAbs)
{
minAbs=target - closest;
result = closest;
}
}
}
}
}
return result;
}
};