C++ simple solution


  • 0
    X
    class Solution {
    public:
        string largestNumber(vector<int>& nums) {
            if(nums.empty()){
                return "";
            }
            vector<string> vec(nums.size());
            for(int i = 0; i < nums.size(); ++i){
                vec[i] = int2string(nums[i]);
            }
            sort(vec.begin(), vec.end(), cmp());
            //for_each(vec.begin(), vec.end(), [](string i){cout<<i<<" ";});
            //cout <<endl;
            string ans = "";
            for(string s : vec){
                ans += s;
            }
            if(ans[0] == '0'){
                return "0";
            }
            return ans;
        }
    private:
        struct cmp{
          bool operator()(const string& lhs, const string& rhs){
              return lhs + rhs > rhs + lhs;
          }  
        };
        string int2string(int x){
            stringstream ss;
            ss << x;
            string tmp;
            ss >> tmp;
            return tmp;
        }
    };

Log in to reply
 

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