• 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; } };
  • 相关阅读:
    wireshark安装
    高效使用搜索引擎
    MFC 网络编程 -- 总结
    MFC Grid control 2.27
    A Popup Progress Window
    Showing progress bar in a status bar pane
    Progress Control with Text
    Report List Controls
    第三方
    CBarChart柱形图类
  • 原文地址:https://www.cnblogs.com/CathyGao/p/3020090.html
Copyright © 2020-2023  润新知