Solution:
Same as 3 sum, actually much simpler than 3 sum, since we only need to record the sum result. Update the closet value every time we update the indices.
Codes:
int threeSumClosest(vector
int close=num[0]+num[1]+num[2];
sort(num.begin(), num.end());
for(int i=0; i
{
int j=i+1;
int k=num.size()-1;
while(j
{
int sum2=num[j]+num[k];
int sum3 = sum2 +num[i];
if(sum3==target)
return target;
else
{
if (abs(close-target)>abs(sum3-target))
close = sum3;
if (sum3>target)
k--;
else
j++;
}
}
}
return close;
}
No comments:
Post a Comment