What's wrong with my code?


  • 1
    L
     Input:	[1,-2,-5,-4,-3,3,3,5], -11
    Output:	[]
    Expected:	[[-5,-4,-3,1]]    
    
    class Solution {
        public:
            vector<vector<int> > fourSum(vector<int> &num, int target) {
                // set<vector<int>> ret;
                vector<vector<int>> ret;
                if(num.size() < 4)
                {
                    return ret;
                }
                sort(num.begin(),num.end());
                for(int i = 0; i < num.size()-3; i++)
                {
                    if(num[i] >target)
                    {
                        break;
                    }
                    for(int j = i+1; j < num.size() - 2; j++)
                    {
                        if((num[i] + num[j]) >target)
                        {
                            break;
                        }
                        int k = j+1;
                        int l = num.size() -1;
                        while(k <l)
                        {
                            if((num[i] + num[j] + num[k] + num[l]) == target)
                            {
                                vector<int> result;
                                result.push_back(num[i]);
                                result.push_back(num[j]);
                                result.push_back(num[k]);
                                result.push_back(num[l]);
                                if(find(ret.begin(),ret.end(),result) == ret.end())
                                {
                                    ret.push_back(result);
                                }
                                k++;
                                l--;
                            }
                            else if((num[i] + num[j] + num[k] + num[l]) > target)
                            {
                                l--;
                            }
                            else
                            {
                                k++;
                            }
                        }
                    }
                }
              return ret;
            }
        };

  • 1
    W

    You need to delete these 2 block in the for loop of i and j....it doesn't make sense =.=

     if(num[i] >target)
        {
              break;
        }
    
       if((num[i] + num[j]) >target)
       {
              break;
        }

  • 0
    L

    Thank you so much! That really helps me!


Log in to reply
 

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