avatar
请问这个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 (jclass 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;
}
};
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。