# 最大数
给定一组非负整数 nums
,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。
注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。
示例 1:
输入:
nums = [10,2]
输出:"210"
示例 2:
输入:
nums = [3,30,34,5,9]
输出:"9534330"
示例 3:
输入:
nums = [1]
输出:"1"
示例 4:
输入:
nums = [10]
输出:"10"
提示:
1 <= nums.length <= 100
0 <= nums[i] <= 109
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
vector nums = {3, 30, 34, 5, 9};
string res = sol.largestNumber(nums);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
string largestNumber(vector &nums)
{
string ans;
for (int i = 0; i < nums.size(); i++)
{
for (int j = nums.size() - 1; j > i; j--)
{
if (to_string(nums[j - 1]) + to_string(nums[j]) > to_string(nums[j]) + to_string(nums[j - 1]))
{
int tmp = nums[j - 1];
nums[j - 1] = nums[j];
nums[j] = tmp;
}
}
ans += to_string(nums[i]);
}
if (ans + "0" == "0" + ans)
return "0";
return ans;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
string largestNumber(vector &nums)
{
string ans;
sort(nums.begin(), nums.end(), [](int a, int b)
{ return to_string(a) + to_string(b) > to_string(b) + to_string(a); });
for (auto it : nums)
{
ans += to_string(it);
}
return ans[0] == '0' ? "0" : ans;
}
};
```
### B
```cpp
class Solution
{
public:
string largestNumber(vector &nums)
{
if (*max_element(nums.begin(), nums.end()) == 0)
return to_string(0);
vector vec(nums.size());
for (int i = 0; i < nums.size(); ++i)
vec[i] = to_string(nums[i]);
sort(vec.begin(), vec.end(), [](const string &s1, const string &s2)
{ return s1 + s2 > s2 + s1; });
return accumulate(vec.begin(), vec.end(), string());
}
};
```
### C
```cpp
class Solution
{
public:
string largestNumber(vector &nums)
{
string res = "";
int n = nums.size();
vector tmp;
for (int i = 0; i < n; i++)
{
tmp.push_back(to_string(nums[i]));
}
sort(tmp.begin(), tmp.end(), compare);
for (int i = 0; i < tmp.size(); i++)
{
res += tmp[i];
}
if ('0' == res[0])
{
return "0";
}
else
{
return res;
}
}
};
```