请问大牛leetcode 3Sum 和4sum的问题# JobHunting - 待字闺中
a*e
1 楼
请问大牛,这两道题在skip 相同元素的时候,为什么要用类似
if(x < num.size()-1 & num[x] == num[x+1]) continue; // Skip same
x
而不是 // if( num[x] == num[x-1]) continue;
我自己写的时候是comment out的语句,但总是出错。没搞懂为啥
3sum的代码如下。非常感谢!
vector > threeSum(vector &num) {
vector> result;
sort(num.begin(), num.end());
for (int x = num.size()-1; x >=2; x--) { // Do it backwards
if(x < num.size()-1 & num[x] == num[x+1]) continue; // Skip same
x
// if( num[x] == num[x-1]) continue;
for (int y = 0, z = x-1; y < z;) {
if(y>0 && num[y]==num[y-1]) { // Skip same y
// if( num[y]==num[y+1]) {
y++;
continue;
}
if(z z--;
continue;
}
int s = num[x] + num[y] + num[z];
if (s > 0)
z--;
if (s < 0)
y++;
if (s == 0) {
vector tmpOne(3);
tmpOne[0] = num[y];
tmpOne[1] = num[z];
tmpOne[2] = num[x];
result.push_back(tmpOne);
y++;z--;
}
}
}
return result;
}
if(x < num.size()-1 & num[x] == num[x+1]) continue; // Skip same
x
而不是 // if( num[x] == num[x-1]) continue;
我自己写的时候是comment out的语句,但总是出错。没搞懂为啥
3sum的代码如下。非常感谢!
vector
vector
sort(num.begin(), num.end());
for (int x = num.size()-1; x >=2; x--) { // Do it backwards
if(x < num.size()-1 & num[x] == num[x+1]) continue; // Skip same
x
// if( num[x] == num[x-1]) continue;
for (int y = 0, z = x-1; y < z;) {
if(y>0 && num[y]==num[y-1]) { // Skip same y
// if( num[y]==num[y+1]) {
y++;
continue;
}
if(z
continue;
}
int s = num[x] + num[y] + num[z];
if (s > 0)
z--;
if (s < 0)
y++;
if (s == 0) {
vector
tmpOne[0] = num[y];
tmpOne[1] = num[z];
tmpOne[2] = num[x];
result.push_back(tmpOne);
y++;z--;
}
}
}
return result;
}