Compact C++ solution using map & reduce


  • 1
    K
    class Solution {
    public:
        string largestNumber(vector<int>& nums) {
            vector<string> snums(nums.size());
            
            transform(
                nums.begin(),
                nums.end(),
                snums.begin(),
                static_cast<string (*)(int)>(to_string)
            );
            
            sort(
                snums.begin(),
                snums.end(),
                [] (string& x, string& y) {
                    return x + y > y + x;
                }
            );
            
            string result = accumulate(
                snums.begin(),
                snums.end(),
                string()
            );
            
            return (result[0] == '0') ? "0" : result;
        }
    };

Log in to reply
 

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