What's wrong with my codes? time limit exceeded! It's O(n^2)?!


  • 0
    Q
    class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            sort(num.begin(),num.end());
            vector<vector<int> > result;
            if(num.size()<3) return result;
            for(auto a=num.begin();a<prev(num.begin(),2);a++)
            {
                auto b=next(a);
                auto c=prev(num.end());
                while(b<c)
                {
                    if(*a+*b+*c<0)
                    {
                        b++;
                    }
                    else if(*a+*b+*c>0)
                    {
                        c--;
                    }
                    else
                    {
                        result.push_back({*a,*b,*c});
                        b++;
                        c--;
                    }
                }
            }
            sort(result.begin(),result.end());
            result.erase(unique(result.begin(),result.end()),result.end());
            return result;
        }
    };

Log in to reply
 

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