Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9]
, the largest formed number is 9534330
.
Note: The result may be very large, so you need to return a string instead of an integer.
Analyse: Write the sort compare function.
Runtime: 24ms
1 class Solution { 2 public: 3 string largestNumber(vector<int>& nums) { 4 string result; 5 if(nums.empty()) return result; 6 7 sort(nums.begin(), nums.end(), compare); 8 for(int i = 0; i < nums.size(); i++) 9 result += to_string(nums[i]); 10 11 if(result[0] == '0') return "0"; 12 return result; 13 } 14 15 static int compare(int a, int b){ 16 string s1 = to_string(a) + to_string(b); 17 string s2 = to_string(b) + to_string(a); 18 return s1 > s2; 19 } 20 };