TLE please help me out !!!!!


  • 0
    T

    class Solution {
    public:
    vector<vector<int>> threeSum(vector<int>& nums) {

        vector<vector<int>> result;
        set<vector<int>> s;
        int n = nums.size();
        std::sort(nums.begin(),nums.end());
        
        if(nums.size() < 3 || nums[0] >= 1 || nums[n - 1] <= -1)
            return result;
        
        for(int i = 0;i < n - 2;i++)
        {
            int j = i + 1;
            int k = n - 1;
            while(j < k)
            {
                if(nums[i] + nums[j] + nums[k] > 0)
                    k--;
                else if(nums[i] + nums[j] + nums[k] < 0)
                    j++;
                else
                {
                    vector<int> vec;
                    vec.push_back(nums[i]);
                    vec.push_back(nums[j]);
                    vec.push_back(nums[k]);
                    s.insert(vec);
                    j++;
                    k--;
                }
            }
        }
        set<vector<int>>::iterator it;
        for(it = s.begin();it != s.end();++it)
            result.push_back(*it);
            
        return result;
    }
    

    };


  • 0
    Z

    Time limit exceeded is usually caused by two reasons. One is running too slow than expected and the other one is running forever somewhere. I suggest you to use a simple test case like -1,2,-1,2 and print out simple message like cout <<"yeaaah, you can't see me"<<endl; in your code line by line until you really cannot see it


  • 0
    T

    Thanks for replying....I think mine is reason one "running too slow than expected" because the test case on which it's failing when running alone(using Run Code) is producing the same output as expected...


  • 0
    Z

    then I suggest to use result.push_back(vector<int> ({nums[i], nums[j], nums[k]})); instead of temporary vector and set then result.


  • 0
    A

    is it solved? I guess it is because the complexity of insertion of set.
    Have you tried to use unordered_set?


Log in to reply
 

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