一、题目描述
https://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993?tpId=13&tqId=11185&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
二、解题思路
自定义一种大小比较方式:
规定:
a
<
b
a<b
a<b 代表a与b拼接在一起的所得值 小于 b 与 a拼接所得数字的值,即ab < ba
按照这种规则对数组进行排序后,所得的数组即能得到最小的数。
三、代码
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>& numbers) {
sort(numbers.begin() , numbers.end() ,cmp );
string res;
for( auto it : numbers)
res += to_string(it);
return res;
}
};