179. Largest Number
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.
way-1
直接利用sort的自定义排序功能。
way-2
利用set的自动排序
static bool is_change(const string& a, const string& b) //如果a < b则交换
{
string ab = a + b;
string ba = b + a;
return ab > ba;
}
class Solution {
public:
string largestNumber(vector<int>& nums)
{
string ret = "";
vector<string> num;
for(auto it : nums)
num.push_back(to_string(it));
sort(num.begin(), num.end(), is_change);
for(int i = 0; i < num.size(); i++)
ret = ret + num[i];
//如果全是0则返回"0"
if (ret[0] == '0')
return "0";
return ret;
}
};
class My_str{
public:
My_str(string s):str(s){}
bool operator<(const My_str &b) const
{
string ab = this->str + b.str;
string ba = b.str + this->str;
return ab > ba;
}
string str;
};
class Solution {
public:
string largestNumber(vector<int>& nums)
{
string ret = "";
multiset<My_str> num;
for(auto it : nums)
num.insert(My_str(to_string(it)));
for(auto it : num)
ret = ret + it.str;
//如果全是0则返回"0"
if (ret[0] == '0')
return "0";
return ret;
}
};