My answer C++ 15ms,please help me improve it


  • 2
    L
    string inttostring(int &i)
    {
        string s;
        stringstream ss(s);
        ss << i;
        return ss.str();
    }
    bool comp(const string &s1, const string &s2) 
    {
        string s3 = s1 + s2;
        string s4 = s2 + s1;
        if(s3 >= s4)
            return true;
        else 
            return false;
    }
    class Solution {
    public:
        string largestNumber(vector<int> &num) {
            int size = num.size();
            vector<string> string1;
            string result;
            int tag = 0;
        for(int i = 1; i <= size; i++) {
            tag += num[i-1];
            string temp = inttostring(num[i-1]);
            string1.push_back(temp);
        }
        if(tag==0)
        return "0";
        std::sort(string1.begin(), string1.end(),comp);
        for(int i=0; i<size;i++)
            result += string1[i];
            return result;
    
        }
    
    };

  • 6
    M

    Basically the same idea, just less code and better check, when we get only zero numbers.

      class Solution {
        public:
            string largestNumber(vector<int> &num) {
                
                int n = num.size();
                vector<string> numstrs(n);
                
                for(int i = 0; i < n; i++)
                {
                    numstrs[i] = to_string(num[i]); // to_string() is standard lib func
                }
                
                sort(numstrs.begin(), numstrs.end(), myCompare);
                
                if (numstrs[n-1] == "0")
                {
                    return "0";
                }
                
                string res;
                for(int i = n-1; i >= 0; i--)
                {
                    res += numstrs[i];
                }
                
                return res;
            }
            
            static bool myCompare (string str1, string str2)
            {
                return (str1 + str2) < (str2 + str1);
            }
        };

  • 0
    P

    Looks good. But I just wanted to add that your last piece of code, where you do "res += numstrs" could be slow for large inputs. You could make it even faster by using stringstream or reserving space ahead of time.


Log in to reply
 

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