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 is 8423201
.
Challenge
Do it in O(nlogn) time complexity.
class Solution {
private:
static bool cmp(const string &a,const string &b){
string ab = a + b;
string ba = b + a;
return ab > ba;
}
public:
/**
*@param num: A list of non negative integers
*@return: A string
*/
string largestNumber(vector<int> &num) {
// write your code here
vector<string> auxVtr(num.size());
for(int i : num)
auxVtr.push_back(to_string(i));
sort(auxVtr.begin(), auxVtr.end(), cmp);
string retStr = "";
for (int i=0; i<auxVtr.size(); i++)
retStr += auxVtr[i];
if(retStr[0] == '0' && retStr.size() > 0)
return "0";
return retStr;
}
};