剑指 Offer 45. 把数组排成最小的数
题目描述
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
解题思路
- 排序,对于x和y,判定大小的规则是
- 如果xy拼接后 < yx拼接,那么x < y
- 将排序结果从小到大拼接
- 字符串到数字用
stoi
、stol
、stoll
- 数字到字符串用
to_string
知识点
数组,排序,字符串
代码
class Solution {
public:
static bool cmp(int x, int y) {
long long int xy = stoll(to_string(x) + to_string(y));
long long int yx = stoll(to_string(y) + to_string(x));
return xy < yx;
}
string minNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), cmp);
string res;
for (const auto& n : nums) {
res += to_string(n);
}
return res;
}
};