题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
解题思路
可以看成是一个排序问题,在比较两个字符串 S1 和 S2 的大小时,应该比较的是 S1+S2 和 S2+S1 的大小,如果 S1+S2 < S2+S1,那么应该把 S1 排在前面,否则应该把 S2 排在前面。这种新的比较方式可以通过自反性、对称性和传递性三方面来证明其合理性。
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
int len = numbers.size();
if(!len) return "";
sort(numbers.begin(), numbers.end(), cmp);
string res;
for(int i=0; i<len; ++i) res += to_string(numbers[i]);
return res;
}
static bool cmp(int a, int b) {
return (to_string(a)+to_string(b)) < (to_string(b)+to_string(a));
}
};
//再来一个
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
sort(numbers.begin(), numbers.end(), [](const int& a,const int& b) {
return to_string(a)+to_string(b)<to_string(b)+to_string(a);});
string res;
for (auto c:numbers) res += to_string(c);
return res;
}
};