题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
解题思路
(1) 先将数组转换成字符串(拼接会带来隐含的大数问题)
(2) 对于数组按照特定的比较规则进行排序
(3) 定义比较的规则---static的函数cmp, 作为sort函数的参数
比较规则的制定:
如果concat(a, b) < concat(b, a), 则认为a< b
如果concat(a, b) > concat(b, a), 则认为a> b
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
string res = "";
if(numbers.size() == 0)
return res;
sort(numbers.begin(), numbers.end(), cmp);
for(int i = 0; i < numbers.size(); i++)
{
res += to_string(numbers[i]);
}
return res;
}
static bool cmp(int a, int b)
{
string A = to_string(a) + to_string(b);
string B = to_string(b) + to_string(a);
return A < B;
}
};