Time Limit Exceeded Problem


  • 0
    F

    I don't understand why my code has a TLE problem. Can anybody figure it out?

    class Solution {
    public:
        vector<vector<int>> fourSum(vector<int>& nums, int target) {
            sort(nums.begin(), nums.end());
            int n = nums.size();
            unordered_map<int, int> maps;
            vector<vector<int>> results;
            for(int i=0; i<n-3; i++){
                if(i>0 && nums[i]==nums[i-1]) continue;
                for(int j=i+1; j<n-2; j++){
                    if(j>i+1 && nums[j]==nums[j-1]) continue;
                    for(int k=j+1; k<n; k++){    
                        int need = target - nums[i] - nums[j] - nums[k];
                        if(maps.find(need) != maps.end()){
                            if(k>j+1 && nums[k] != need && nums[k] == nums[k-1]) continue;
                            if(k>j+2 && nums[k] == need && nums[k] == nums[k-2]) continue;
                            results.push_back({nums[i], nums[j],need, nums[k]});
                        }
                        else{
                            maps[nums[k]] = k;
                        }
                    }
                    
                    maps.erase(maps.begin(), maps.end());
                }
                    
            }
            return results;    
        }
    };
    

Log in to reply
 

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