题目:
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.
思路:
这道题目的思路不难,主要有三个步骤:1)重写一个特殊的比较函数,使得首位越大的数字排的越靠前;2)利用步骤1)提供的比较函数进行排序;3)将排好序的数字依次转换为字符串,并且连接起来。这里需要注意一个特殊情况,就是所有数字都是0的情况,此时不能返回“00000”等样子,而要返回“0”。我原来写的比较函数有好几十行,但时候后来发现网上有同学用C++的stl提供的to_string方法,巧妙地实现了需要的功能,代码量立即下降到十行之内。
代码:
class Solution {
public:
string largestNumber(vector<int>& nums) {
if (nums.size() == 0) {
return "";
}
auto cmp = [](int a, int b) {
return to_string(a) + to_string(b) > to_string(b) + to_string(a);
};
sort(nums.begin(), nums.end(), cmp);
string ret;
for (auto val : nums) {
ret += to_string(val);
}
return ret[0] == '0' ? "0" : ret;
}
};
构造最大数值
本文介绍了一种算法,用于将非负整数列表重新排列形成最大的可能数值。通过自定义比较函数和排序策略,确保数字按最优顺序排列。最终,将排序后的数字转换为字符串并连接起来。
363

被折叠的 条评论
为什么被折叠?



