s*******y 发帖数: 105 | 1 在leetcode网上看到一种解法,感觉是对的,但是通不过OJ,显示Time Limit
Exceeded, 懂的童鞋给分析下code哪里有问题,3ks~
class Solution {
public:
vector > threeSum(vector &num) {
// Start typing your C/C++ solution below
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(num.begin(),num.end());
vector > r;
vector a;
int len = num.size();
if( len < 3 || num[0] > 0 || num[len-1] < 0 )
{
return r;
}
int i,j,k,sum,tempj,tempk,prev=num[0]-1;
for( i = 0; i < len-2 && num[i] < 0; ++i )//outer for
{
if( num[i] == prev )
{
continue;
}
prev = num[i];
for( j = i+1; k = len-1; j < k) //inner for
{
sum = num[i] + num[j] + num[k];
if( sum == 0 )
{
a.push_back(num[i]);
a.push_back(num[j]);
a.push_back(num[k]);
r.push_back(a);
a.clear();
tempj = num[j];
tempk = num[k];
while( j < k && num[j] == tempj )
++j;
while( k > j && num[k] == tempk )
--k;
}
else if( sum < 0 )
{
tempj = num[j];
while( j < k && num[j] == tempj )
++j;
}
else
{
tempk = num[k];
while( k > j && num[k] == tempk )
--k;
}
}//end inner for
}//end outer for
if( i < len-2 && num[i] == 0 && num[i+1] == 0 && num[i+2] == 0 )
{
a.assign(3,0);
r.push_back(a);
}
return r;
}
}; | g****y 发帖数: 240 | 2 for( j = i+1; k = len-1; j < k) //inner for
这个。。。。不对吧。 |
|