Why my c++ solution got runtime error?


  • 0
    N
    class Comp
    {
        public:
        bool operator()(const string &l, const string &r)
        {
            return r>=l;
        }
    };
    
    string largestNumber(vector<int> &num) {
        vector<string> s;
    
        int k = 0;
        while (!num[k] && k < num.size()) k++;
        if (k == num.size()) return "0";
    
        for(auto it=num.begin();it!=num.end();it++)
        {
            s.push_back(to_string(*it));
        }
    
        sort(s.begin(), s.end(), Comp());
    
        string res;
        for(auto it=s.begin();it!=s.end();it++)
        {
            res.append(*it);
        }
        return res;
    }

  • 4
    D

    I'm not sure if your code is correct but I do have a tip for why you got RE. When you rewrite the cmp function for std::sort, Do not return true when two elements are equal. The implementation of std::sort do not have a boundary detection, thus if you return true when two elements are equal, the iterator may probably go out.

    bool operator()(const string &l, const string &r)
        {
            return r>=l;
        }
    

    This part can be wrong.


  • 0
    N

    I think I know why it is got runtime error. It is here (!num[k] && k < num.size()) .
    k<num.size() has to be checked first. Also, I agree with you that my algorithm is incorrect.


  • 0
    N

    I think I know why it is got runtime error. It is here (!num[k] && k < num.size()) . k<num.size() has to be checked first.

    but again, the algorithm is still incorrect.


Log in to reply
 

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