标签:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int differ;
int length = nums.size();
bool mark = true;
for(int i = 0; i < length - 2; i++) {
int secondTarget = target - nums[i];
int start = i + 1;
int end = length - 1;
for(; start < end; ) {
if(mark) {
differ = nums[start] + nums[end] - secondTarget;
if(differ == 0)
break;
mark = false;
if(nums[start] + nums[end] - secondTarget < 0)
start++;
if(nums[start] + nums[end] - secondTarget > 0)
end--;
}else {
if(abs(nums[start] + nums[end] - secondTarget) < abs(differ))
differ = nums[start] + nums[end] - secondTarget;
if(differ == 0)
break;
if(nums[start] + nums[end] - secondTarget < 0)
start++;
if(nums[start] + nums[end] - secondTarget > 0)
end--;
}
}
if(differ == 0)
break;
}
return target + differ;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/guanzhongshan/article/details/46914101