58. 把数组排成最小的数
题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
例如输入数组 [3,32,321],则打印出这 3 个数字能排成的最小数字 321323。
数据范围
数组长度 [0,500]。
样例
输入:[3, 32, 321]
输出:321323
算法1 重定义比较函数
算法流程
定义了一种新的比较运算
a < b <==> ab < ba
可以排序:满足反对称性和传递
排出来的一定最小:反证法
C++ 代码
class Solution {
public:
static bool cmp(int a, int b)
{
auto as = to_string(a), bs = to_string(b);
return as + bs < bs + as;
}
string printMinNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), cmp);
string res;
for(auto c : nums) res += to_string(c);
return res;
}
};
总结
学习自定义比较函数