Why am I getting Output limit exceeded in 3Sum?


  • 0
    H

    class Solution {

    public:

    vector<vector<int> > threeSum(vector<int> &num)
    {

    bool flag = false;
    vector<vector<int> > sum;
    vector<int> temp = num;
    sort(temp.begin(), temp.end());
    if (num.size() < 3 || temp[0] > 0)
    return sum;
    
    for (int i = 1; i != num.size() - 1; i++)
    {
        int left = i - 1, right = i + 1;
        while(left>=0 && right < num.size())
        {
            if (temp[left] + temp[i] + temp[right] == 0)
            {
                vector<int> sub;
                sub.push_back(temp[left]);
                sub.push_back(temp[i]);
                sub.push_back(temp[right]);
                if (!flag)
                {
                    flag = true;
                    sum.push_back(sub);
                }
                else if(sub != sum[sum.size()-1])
                {
                    sum.push_back(sub);
                }
                left--;
                right++;
            }
            else if(temp[left] + temp[i] + temp[right] < 0)
            {
                right++;
            }
            else
                left--;
        }
    }
    return sum;
    

    }
    };


Log in to reply
 

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