Don't know why this solution always complaints that "Output Limit Exceeded (C++)"?


  • 0
    R
    vector<vector<int> > threeSum(vector<int> &num) 
    {
        vector<vector<int> > ret;
        const int target = 0;
        if (num.size() < 3)
            return ret;
    
        sort (num.begin(), num.end());
        
        for (auto it=num.begin(); it<prev(num.end(), 2); ++it)
        {
            auto begin = next(it);
            auto end = prev(num.end());
            while (begin < end)
            {
                if (*begin + *end + *it < target)
                {
                    ++begin;
                }
                else if (*begin + *end + *it > target)
                {
                    --end;
                }
                else
                {
                    ret.push_back({*it, *begin, *end});
                    ++begin;
                    --end;
                }
            }
        }
    
        sort(ret.begin(), ret.end());
        ret.erase(unique(ret.begin(), ret.end()), ret.end());
        return ret;
    }

  • 1
    Z
    enter code here
    

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //// I think you can modify the for loop like this:

    // do not know why some code goes outside

    vector<int>::iterator itLast;

    for (auto it=num.begin(); it<prev(num.end(), 2); ++it)
    {
    if (it!=num.begin()&&(*itLast)==(*it)) continue; // remove duplicate

        auto begin = next(it);
        auto end = prev(num.end());
        while (begin < end)
        {
            if (*begin + *end + *it < target)
            {
                ++begin;
            }
            else if (*begin + *end + *it > target)
            {
                --end;
            }
            else
            {
                ret.push_back({*it, *begin, *end});
                ++begin;
                --end;
            }
        }
    
        itLast = it;                                                        // record last element
    }
    

    It works for me.


  • 0
    R

    thank you so much!


  • 0
    A

    It does work! But how do the remove-duplicate-lines improve the code that much?


Log in to reply
 

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