No idea why I got Time limit exceed


  • 0
    T

    I think everything is right, but I cannot pass the test ....
    On my machine, I get the result quickly.

    vector<vector<int> > fourSum(vector<int> &num, int target) {
    
    if (num.size()<4) return vector< vector<int> >();
    sort(num.begin(), num.end());
    vector< vector<int> > set;
    for(int idf=0; idf<num.size()-3; idf++) {
        for(int ids=idf+1; ids<num.size()-2; ids++) {
            int idt=ids+1, ide=num.size()-1;
            while(idt<ide) {
                int curTgt = num.at(idf)+num.at(ids)+num.at(idt)+num.at(ide);
                if (curTgt==target) {
                    vector<int> ans(4, 0);
                    ans.at(0) = num.at(idf); ans.at(1) = num.at(ids);
                    ans.at(2) = num.at(idt); ans.at(3) = num.at(ide);
                    set.push_back(ans);
                    idt++; ide--;
                    while(idt<ide && num.at(idt)==num.at(idt-1)) idt++;
                    while(ide>idt && num.at(ide)==num.at(ide+1)) ide--;
                }
                else if (curTgt<target) {
                    idt++;
                    while(idt<ide && num.at(idt)==num.at(idt-1)) idt++;
                }
                else {
                    ide--;
                    while(ide>idt && num.at(ide)==num.at(ide+1)) ide--;
                }
            }
            while(ids<num.size()-2 && num.at(ids)==num.at(ids+1)) ids++;
        }
        while(idf<num.size()-3 && num.at(idf)==num.at(idf+1)) idf++;
    }
    return set;
    

    }


Log in to reply
 

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