题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
时间限制:1秒
空间限制:32768K
热度指数:74280
思路
对vector容器内的数据进行排序。
将 a 和 b 转为 string 后,若 a + b < b + a, 则 “a 排在前” 的规则排序;
例如, 2 21 ,因为 212 < 221 ,所以排序后为 21 2
参考代码中,使用到了 cmp() 函数来自定义 sort() 函数的排序功能,
to_string() 可以将 int 转化为 string。
有小伙伴问到为什么 cmp() 函数要用到 static?
其实大家可以试试不用static 会发生什么?会报错。
sort中的比较函数 cmp要声明为静态成员函数或全局函数,不能作为普通成员函数。
因为,非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,
因此无法在sort中调用非静态成员函数。静态成员函数或者全局函数是不依赖于具体对象的,
可以独立访问,同时静态成员函数不可以调用类的非静态成员。
代码中,return A < B 表示升序排序,若你想改成降序,改为 return A > B 就表示降序排序。
参考代码
class Solution {
public:
static bool cmp(int a, int b) {
string A = "";
string B = "";
A += to_string(a);
A += to_string(b); //ab
B += to_string(b);
B += to_string(a); //ba
return A < B; //升序排序
}
string PrintMinNumber(vector<int> numbers) {
string answer = "";
sort(numbers.begin(), numbers.end(), cmp);
for (int i = 0; i < numbers.size(); i++) {
answer += to_string(numbers[i]);
}
return answer;
}
};