Leetcode 剑指 Offer 45. 把数组排成最小的数
题目
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
示例 1:
输入: [10,2]
输出: "102"
示例 2:
输入: [3,30,34,5,9]
输出: "3033459"
思路
- 将数组自定义排序
- 以第一个例子来说, 102 < 210, 所以最终排序结果就是10,2, 顺序连接即可
代码 —— c++
class Solution {
public:
string minNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), [](const int& a, const int& b) {
auto _a = to_string(a), _b = to_string(b);
return _a + _b < _b + _a;
});
string res;
for (auto& data:nums) {
res += to_string(data);
}
return res;
}
};