C++ solution, sort function is essence point.


  • 6
    class Solution {
    public:
      string largestNumber(vector<int>& nums) {
        string ret = "";
        sort(nums.begin(), nums.end(), compare);
        for (int i = 0; i < nums.size(); i ++)
        {
          ret += to_string(nums[i]);
        }
        if (ret[0] == '0')
        {
          return "0";
        }
        return ret;
      }
      static bool compare(int a, int b)
      {
        string x = to_string(a);
        string y = to_string(b);
    
        return x + y > y + x;
      }
    };
    

Log in to reply
 

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