Why am I getting "Output Limit Exceeded" result?


  • 0
    B
    class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            typedef vector<int> numbers;
            vector<numbers> result;
            sort(num.begin(), num.end());
            for (int x = 2; x < num.size(); x++) {
                for (int y = 0, z = x-1; y < z;) {
                    int s = num[x] + num[y] + num[z];
                    if (s > 0)
                        z--;
                    if (s < 0)
                        y++;
                    if (s == 0) {
                        vector<int> tmpOne(3);
                        tmpOne[0] = num[y];
                        tmpOne[1] = num[z];
                        tmpOne[2] = num[x];
                        result.push_back(tmpOne);
                        y++;z--;
                    }
                }
            }
            return result;
        }
    };

  • 8
    P

    Simply because you have many duplicates in your result

    You have to be careful with duplicates.

    class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            typedef vector<int> numbers;
            vector<numbers> result;
            sort(num.begin(), num.end());
            for (int x = num.size()-1; x >=2; x--) { // Do it backwards
            	if(x < num.size()-1 & num[x] == num[x+1]) continue; // Skip same x
                for (int y = 0, z = x-1; y < z;) {
                	if(y>0 && num[y]==num[y-1]) { // Skip same y
                		y++;
                		continue;
                	}
                	if(z<x-1&&num[z]==num[z+1]) { // Skip same z
                		z--;
                		continue;
                	}
                    int s = num[x] + num[y] + num[z];
                    if (s > 0)
                        z--;
                    if (s < 0)
                        y++;
                    if (s == 0) {
                        vector<int> tmpOne(3);
                        tmpOne[0] = num[y];
                        tmpOne[1] = num[z];
                        tmpOne[2] = num[x];
                        result.push_back(tmpOne);
                        y++;z--;
                    }
                }
            }
            return result;
        }
    };

Log in to reply
 

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