您的位置:首页 > 职场人生

13_leetcode_3Sum Closest

2014-06-05 08:12 260 查看
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.

1.数组排序;2.当找到三个元素的值与目标值相等,直接返回 3.找到最接近的情况,分为大于目标值和小于目标值两种情况

int threeSumClosest(vector<int> &num, int target)
{
if(num.size() <= 2)
return 0;

int result = num[0] + num[1] + num[2];

sort(num.begin(), num.end());

int size = (int)num.size();
for(int i = 0; i < size - 2; i++)
{
if(i == 0 || num[i] != num[i-1])
{
int leftValue = target - num[i];
int left = i + 1;
int right = size - 1;

while(left < right)
{
if(num[left] + num[right] == leftValue)
{
return target;
}
else if(num[left] + num[right] > leftValue)
{
if(num[left] + num[right] - leftValue <= abs(result - target))
{
result = num[left] + num[right] + num[i];
}
right--;
}
else
{
if(leftValue - num[left] - num[right] <= abs(result - target))
{
result = num[left] + num[right] + num[i];
}
left++;
}
}

}
}

return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息