思路: 对 vector 容器内的数据进行排序, 按照将 a 和 b 转为 string 后, 若 a+b<b+a,a 排在前的规则排序.
- class Solution {
- public:
- string PrintMinNumber(vector numbers) {
- int len=numbers.size();
- if(len==0)
- return "";
- //cmp 为下方的静态成员函数
- 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)
- {
- string A=to_string(a)+to_string(b);
- string B=to_string(b)+to_string(a);
- return A<B;
sort 中的比较函数 compare 要声明为静态成员函数或全局函数, 不能作为普通成员函数, 否则会报错. 因为: 非静态成员函数是依赖于具体对象的, 而 std::sort 这类函数是全局的, 因此无法再 sort 中调用非静态成员函数. 静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问, 无须创建任何对象实例就可以访问. 同时静态成员函数不可以调用类的非静态成员.
来源: http://www.bubuko.com/infodetail-3060283.html