【Leetcode】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).
1st (6 tries )
class Solution
{
public:
int threeSumClosest(vector<int> &num, int target)
{
// Note: The Solution object is instantiated only once and is reused by each test case.
int diff = INT_MAX;
int sum;
int ret;
sort(num.begin(),num.end());
for(int i = 0;i < num.size();++i)
{
int start = i + 1;
int end = num.size() - 1;
while(end > start)
{
sum = num[i] + num[start] + num[end];
if(sum == target)
return sum;
else
{
int dis = abs(sum - target);
if(dis < diff)
{
diff = dis;
ret = sum;
}
if(sum > target)
{
end--;
}
if(sum < target)
{
start++;
}
}
}
}
return ret;
}
};
2nd ( 2 tries )
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
sort(num.begin(),num.end());
int first,second,third,mingap,ans;
mingap = INT_MAX;
for(first = 0;first < num.size() - 2;first++) {
second = first + 1;
third = num.size() - 1;
while(second < third) {
int sum = num[first] + num[second] + num[third];
if(sum == target) {
return sum;
}
else if(sum > target) {
if(abs(sum-target) < mingap) {
mingap = abs(sum-target);
ans = sum;
}
third--;
}
else {
if(abs(sum-target) < mingap) {
mingap = abs(sum-target);
ans = sum;
}
second++;
}
}
}
return ans;
}
};

浙公网安备 33010602011771号