题目
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
思路
遇到这个题,全排列当然可以做,但是时间复杂度为O(n!)。在这里我们自己定义一个规则,对拼接后的字符串进行比较。
排序规则如下:
- 若ab > ba 则 a 大于 b,
- 若ab < ba 则 a 小于 b,
- 若ab = ba 则 a 等于 b;
根据上述规则,我们需要先将数字转换成字符串再进行比较,因为需要串起来进行比较。比较完之后,按顺序输出即可。
问题:
stl中的sort(),我们重新了compare比较函数。为什么是static
当cmp函数写在类外时可以不加static
写在类内时,要加上static,
lexicographical_compare 最后要求的是一个普通函数指针,而不是成员函数指针,所以要加static:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution
{
public:
string printMinNumber(vector<int> numbers)
{
int len = numbers.size();
if (len == 0)
return “”;
sort(numbers.begin(), numbers.end(), cmp);
string result;
for (int i = 0; i < len; i++)
{
result += to_string(numbers[i]);
}
return result;
}
private:
static bool cmp(int a, int b) //为什么是static
{
string aa = to_string(a) + to_string(b);
string bb = to_string(b) + to_string(a);
return aa < bb; //升序从小到大排列 ab < ba
}
};
int main()
{
Solution s;
vector<int> number{ 3, 321, 23, 34 };
for (auto i : s.printMinNumber(number))
cout << i;
cout << endl;
system("pause");
return 0;
}