题目描述
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
示例 1:
输入: [10,2]
输出: “102”
示例 2:
输入: [3,30,34,5,9]
输出: “3033459”
提示:
0 < nums.length <= 100
说明:
输出结果可能非常大,所以你需要返回一个字符串而不是整数
拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0
题解
设数组 nums 中任意两数字的字符串为 x 和 y ,则规定 排序判断规则 为:
- 若拼接字符串 x + y > y + x,则字符串 xy “大于” yx ;
- 反之,若 x + y < y + x,则字符串 xy “小于” xy ;
注意:
字符串比较大小就是先比较第一个字符大小,再比较后面的字符
C++ lambda表达式与函数对象
题解1: 快速排序
class Solution {
public:
string minNumber(vector<int>& nums) {
vector<string> strs;
for(int i = 0; i < nums.size(); i++)
strs.push_back(to_string(nums[i]));
quickSort(strs, 0, strs.size() - 1);
string res;
for(string s : strs)
res.append(s);
return res;
}
private:
void quickSort(vector<string>& strs, int l, int r) {
if(l >= r) return;
int i = l, j = r;
while(i < j) {
while(strs[j] + strs[l] >= strs[l] + strs[j] && i < j) j--;
while(strs[i] + strs[l] <= strs[l] + strs[i] && i < j) i++;
swap(strs[i], strs[j]);
}
swap(strs[i], strs[l]);
quickSort(strs, l, i - 1);
quickSort(strs, i + 1, r);
}
};
复杂度分析:
- 时间复杂度 O(NlogN) : N 为最终返回值的字符数量( strs 列表的长度 ≤ N );使用快排或内置函数的平均时间复杂度为O(NlogN) ,最差为O(N2) 。
- 空间复杂度 O(N) : 字符串列表strs 占用线性大小的额外空间。
题解2:lamda表达式自定义排序规则
class Solution {
public:
string minNumber(vector<int>& nums) {
vector<string> strs;
string res;
for(int i = 0; i < nums.size(); i++)
strs.push_back(to_string(nums[i]));
sort(strs.begin(), strs.end(), [](string& x, string& y){ return x + y < y + x; });
for(int i = 0; i < strs.size(); i++)
res.append(strs[i]);
return res;
}
};
参考
剑指 Offer 45. 把数组排成最小的数(自定义排序,清晰图解)
C++ 先转换成字符串再组合
字节题库 - #剑45 - 中等 - 把数组排成最小的数 - 1刷