最大数
定义最优排序规则若a+b > b+a,则a应排在b前面
class Solution {
public:
string largestNumber(vector<int>& nums) {
// 将所有数字转为字符串
vector<string> strNums;
for (int num : nums) {
strNums.push_back(to_string(num));
}
// 自定义排序规则
sort(strNums.begin(), strNums.end(), [](const string& a, const string& b) {
return a + b > b + a;
});
// 处理全0的情况
if (strNums[0] == "0") {
return "0";
}
// 拼接所有字符串得到结果
string res;
for (const string& s : strNums) {
res += s;
}
return res;
}
};
时间复杂度: O(nlogn×L)空间复杂度: O(n×L)
