Why my code with Time Limit Exceeded?Please help


  • 0
    L

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

        vector<vector<int> > result;
        if(num.size()<3)
            return result;
        sort(num.begin(),num.end());
        int i = 0;
        while(i < num.size()-1){
            if(i!=0 && num[i] ==num[i-1]) continue;
            int j = i + 1, k = num.size()-1;
            int sum;
            while(j < k){
                sum = num[i] + num[j] + num[k];
                if(sum== 0) {
                        vector<int> one;
                        one.push_back(num[i]);
                        one.push_back(num[j]);
                        one.push_back(num[k]);
                        result.push_back(one);
                        while(++j<k&&num[j]==num[j-1]){}
                        while(j<--k&&num[k]==num[k+1]){}
                }
                else if(sum <0) j++;
                else k--;
            }
            i++;
        }
        return result;
    }
    

    };

    Thx~


  • 0
    Y

    if(i!=0 && num[i] ==num[i-1]) continue:

    You are not updating i there, which causes infinite loop on the test case {0,0,0}, simply replace

    continue;

    by

    {i++;continue;}

    would do.

    Cheers.


  • 0
    L

    Thanks a lot.You've really done me a big favor


Log in to reply
 

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