I think it's the most straightforward answer, although it's O(n^3)


  • 0
    R

    It got passed anyway.

    class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            vector<vector<int>> res;
            if(num.size() < 3) return res;
            sort(num.begin(), num.end());
            int infiniteInt = numeric_limits<int>::max();
            int tmpI = infiniteInt;
            int tmpJ = tmpI;
            int tmpK = tmpJ;
            for(int i = 0; i < num.size(); i++)
            {
                if(tmpI == num[i]) continue;
                for(int j = i+1; j < num.size(); j++)
                {
                    if(tmpJ == num[j]) continue;
                    for(int k = j+1; k < num.size(); k++)
                    {
                        if(tmpK == num[k]) continue;
                        if(num[i] + num[j] + num[k] == 0)
                        {
                            vector<int> a;
                            a.push_back(num[i]);
                            a.push_back(num[j]);
                            a.push_back(num[k]);
                            res.push_back(a);
                        }
                        tmpK = num[k];
                    }
                    tmpK = infiniteInt;
                    tmpJ = num[j];
                }
                tmpJ = infiniteInt;
                tmpI = num[i];
            }
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.