前两个循环,第三个二分查找
用flag标识去重
事先先排序
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
if( num.size() < 3)
return vector< vector< int> >();
vector< vector< int> > res;
sort( num.begin(), num.end());
int flagi = INT_MAX, flagj = INT_MAX;
for( int i = 0; i < num.size(); ++i){
if( flagi == num[i])
continue;
flagi = num[i];//去重,如果用set会TLE
for( int j = i + 1; j < num.size(); ++j){
if( flagj == num[j])
continue;
flagj = num[j];//去重,如果用set会TLE
if( binarySearch( num, 0-num[i]-num[j], j+1, num.size()-1)){
vector< int> tmp;
tmp.push_back(num[i]);
tmp.push_back(num[j]);
tmp.push_back(0-num[i]-num[j]);
res.push_back(tmp);
}
}
}
return res;
}
bool binarySearch( vector< int> &num, int n, int left ,int right){
if( left > right)
return false;
int mid = ( left + right) >> 1;
if( n == num[mid])
return true;
else if( n >= num[mid])
return binarySearch( num, n, mid+1, right);
else
return binarySearch( num, n, left, mid-1);
}
};