【题目】
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.
【分析】
组合这些数字得到最大,贪心的考虑,即对于任何两个数的组合,长度一样,选择字典序较大的组合,就可以全局最大。想到用sort排序,自己写比较函数。要注意特例:所有数字为0.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
using namespace std;
class Solution {
public:
static bool des (const string &a, const string &b)
{
string ab,ba;
ab = a+ b;
ba = b+a;
return ab >ba;
}
string largestNumber(vector<int> &num)
{
vector<string> numstr;
bool allzero = true;
for(int k:num)
{
if(k != 0) allzero = false;
stringstream s1;
s1 << k;
string tmp;
s1 >> tmp;
numstr.push_back(tmp);
}
if(allzero)
return "0";
sort(numstr.begin(), numstr.end(), des);
string result;
for (string str : numstr)
{
result+= str;
}
return result;
}
};
int main()
{
Solution s;
vector<int> v{3,30,34,5,9};
cout << s.largestNumber(v)<< endl;
return 0;
}
上面使用到了c++的一些特性,如stringstream,记得如果要多次使用stringstream对象,必须用clear()重置。