Why my code Time Limit Exceeded?


  • 0
    S
    class Solution {
    public:
        vector<vector<int> > fourSum(vector<int> &num, int target) {
        vector<vector<int> > result;
    	map<int,vector<vector<int> > > two_sum;
    	for (int i = 0; i < num.size(); i++)
    	{
    		for (int j = i + 1; j < num.size(); j++)
    		{
    			int sum = num[i] + num[j];
    			if (two_sum.count(sum))
    			{
    				vector<vector<int> > a = two_sum[sum];
    				a.push_back({ i, j });
    				two_sum.erase(sum);
    				two_sum.insert(pair<int, vector<vector<int> > >(sum, a));
    			}
    			else
    			{
    				two_sum.insert(pair<int, vector<vector<int> > >(sum, { { i, j } }));
    			}
    		}
    	}
    	map<int, vector<vector<int> > >::iterator it;
    	map<vector<int>, int> m_result;
    	for (it = two_sum.begin(); it != two_sum.end(); it++)
    	{
    		int re = target - it->first;
    		if (two_sum.count(re))
    		{
    			for (int i = 0; i < it->second.size(); i++)
    			{
    				for (int m = 0; m < two_sum[re].size(); m++)
    				{
    					int tag = 0;
    					vector<int> index;
    					for (int j = 0; j < 2; j++)
    					{
    						index.push_back(num[it->second[i][j]]);
    						index.push_back(num[two_sum[re][m][j]]);
    						for (int n = 0; n < 2; n++)
    						{
    							if (it->second[i][j] == two_sum[re][m][n])
    							{
    								tag = 1;
    							}
    						}
    					}
    					if (tag == 0)
    					{
    						sort(index.begin(), index.end());
    						m_result.insert(pair<vector<int>, int>(index, 1));
    					}
    				}
    			}
    		}
    	}
    	map<vector<int>, int>::iterator itm;
    	for (itm = m_result.begin(); itm != m_result.end(); itm++)
    	{
    		result.push_back(itm->first);
    	}
    	return result;
    }
    

    };


Log in to reply
 

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