C++ 8ms solution, sort()


  • 2
    class Solution {
    public:
    static bool compare(string a, string b){
        return a+b<b+a; 
    }
    string largestNumber(vector<int>& nums) {
        if (nums.empty()) return "";
        vector<string> numstr;
        for (int i=0;i<nums.size();i++){
            numstr.push_back(to_string(nums[i]));
        }
        sort(numstr.begin(),numstr.end(),compare);
        string res="";
        for (int i=nums.size()-1;i>=0;i--){
            res+=numstr[i];
        }
        if (compare("0",res)) return res;
        else return "0";
    }
    };

  • 0
    O

    Better use

    static bool compare(int i, int j)
        {
            return to_string(i) + to_string(j) > to_string(j) + to_string(i);
        }
    

    this will help to avoid using one more vector of strings, just sort ur vector of ints


  • 0

    Using my way, each number needs to be transferred to string once. However, using your way, each of them will be transferred almost N times, maybe log(N). You save some space, but waste more time calling to_string(). It is just a trade-off between space and speed.


Log in to reply
 

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