您的位置:首页 > 其它

LeetCode: 3SumClosest

2015-04-12 13:09 246 查看
Title :

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).


int threeSumClosest(vector<int> &num, int target){
sort(num.begin(),num.end());
int min = INT_MAX;
int result;
for (int i = 0 ; i < num.size()-2; i++){
if (i > 0 && num[i] == num[i-1])
continue;
int left = i+1;
int right = num.size()-1;
int goal = target - num[i];
while (left < right){
int diff = abs(target - num[left] - num[right] - num[i]);
if (diff < min){
min = diff;
result = num[left] + num[right] + num[i];
}
if (num[left] + num[right] < goal){
while (left < right && (num[left] == num[left+1]))
left++;
left++;
}else if (num[left] + num[right] > goal){
while (left < right && (num[right] == num[right-1]))
right--;
right--;
}else{
return target;
}
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: