Because strings can be compared lexicographically, you can write your own collation rule, CMP, and then convert all the integers in the array to strings and sort them according to your own rules.

After sorting, you concatenate all the strings, which is the largest integer they can form.

Note the special case, if the array is all zeros, we don’t want to print “00000… If the first element in the array is 0, return “0”; It’ll be ok.

The code is as follows:

class Solution { public: static bool cmp(int a, int b) { return to_string(a) + to_string(b) > to_string(b) + to_string(a); } string largestNumber(vector<int>& nums) {sort(nums.begin(), nums.end(), CMP); If (nums[0] == 0) {// return "0"; } string res; for(int i = 0; i < nums.size(); // to_string(nums[I]); } return res; }};Copy the code