请问这个3sumClosest# JobHunting - 待字闺中
G*n
1 楼
Find three integers in S such that the sum is closest to a given number.
下面的code没问题。我想优化一下,skip那些重复的数,但加上下面这2个while语句然
后返回的结果就错了,搞不懂哪里的问题。
//while (j // while (j class Solution {
public:
int threeSumClosest(vector &num, int target) {
int sum = INT_MIN;
int minDist = INT_MAX;
if (num.size()<3) return sum;
sort(num.begin(), num.end());
for (int i = 0; i {
int j=i+1, k=num.size()-1;
while(j {
int s = num[i]+num[j]+num[k];
int diff = abs(s-target);
if (diff < minDist)
{
minDist = diff;
sum = s;
}
//while (j // while (j
if (s {
j++;
}
else if (s>target)
{
k--;
}
else
{
return sum;
}
}
while (i }
return sum;
}
};
下面的code没问题。我想优化一下,skip那些重复的数,但加上下面这2个while语句然
后返回的结果就错了,搞不懂哪里的问题。
//while (j
public:
int threeSumClosest(vector
int sum = INT_MIN;
int minDist = INT_MAX;
if (num.size()<3) return sum;
sort(num.begin(), num.end());
for (int i = 0; i
int j=i+1, k=num.size()-1;
while(j
int s = num[i]+num[j]+num[k];
int diff = abs(s-target);
if (diff < minDist)
{
minDist = diff;
sum = s;
}
//while (j
if (s
j++;
}
else if (s>target)
{
k--;
}
else
{
return sum;
}
}
while (i
return sum;
}
};