Given a list of non negative integers, arrange them such that they form the largest number.
Notice
The result may be very large, so you need to return a string instead of an integer.
Example
Given [1, 20, 23, 4, 8]
, the largest formed number is8423201
.
Analyse: to determine how to place a, b, we could combine a and b in string way and compare to_string(a) + to_string(b), to_string(b) + to_string(a). Aftersorting, it could be 00000008 or 0000000, we need to check whether there is consecutive 0s in the highest index. Lambda is used to sort self-defined comparator.
Runtime: 20ms.
1 class Solution { 2 public: 3 /** 4 *@param num: A list of non negative integers 5 *@return: A string 6 */ 7 string largestNumber(vector<int> &num) { 8 // write your code here 9 string result; 10 if (num.empty()) return result; 11 sort(num.begin(), num.end(), [](int a, int b) { 12 // regard a, b as string, append b to a and a to b 13 // compare a + b and b + a 14 string ab = to_string(a) + to_string(b); 15 string ba = to_string(b) + to_string(a); 16 return ab < ba; 17 }); 18 int i = num.size() - 1; 19 while (i >= 0 && !num[i]) i--; 20 while (i >= 0) 21 result += to_string(num[i--]); 22 return result.empty() ? "0" : result; 23 } 24 };