LeetCode - 3Sum
Expand the 2Sum solver to 3Sum:
for every specific a, find the other two b&c that b+c=-a.
so, it can be solved in O(n^2).
1. generic "find" function:
iterator = find(vec.begin(), vec.end(), vecElem);
if(iterator == vec.end()) cout<<"no find the vecElem in vec!"<<endl;
Attach code:
bool compare(const int& a, const int& b) { return (a<b); } inline bool nofindit(const vector<vector<int> >& vec, const vector<int> elem) { for(int i=0; i<vec.size(); i++) { if(vec[i] == elem) { return false; } } return true; }
class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function sort(num.begin(), num.end(), compare); int len = num.size(); int a,b,c,sum; int j; int k; vector<int> triplet(3,0); vector<vector<int> > ret; vector<vector<int> >::iterator findit; for(int i=0; i<=len-3; i++) { a = num[i]; j=i+1; k=len-1; while(j<k) { b = num[j]; c = num[k]; sum = a+b+c; if( sum == 0) { triplet[0]=a; triplet[1]=b; triplet[2]=c; //findit = find(ret.begin(),ret.end(),triplet); //if(findit==ret.end()) if( nofindit(ret, triplet) ) { ret.push_back(triplet); } j++;k--; } else if( sum > 0) { k--; } else { j++; } } } return ret; } };
posted on 2013-04-14 11:48 highstar88 阅读(174) 评论(0) 编辑 收藏 举报