题目描述:
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3, 32, 321},则打印出这3个数字能排成的最小数字321323。
分析:
完整代码:
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
//声明一个变量 lenght 来获取 numbers 的个数
int length = numbers.size();
//声明一个变量 strNumbers ,用来存放 char 类型数组
string strNumbers = "";
//检查输入的合法性
if(numbers.empty() || length <= 0)
return strNumbers;
//声明一个字符串容器,用来存放
vector<string> array;
//遍历整个数组的元素
for(int i = 0; i < length; ++i)
//将 numbers 中的元素压入到 array 中
array.push_back(to_string(numbers[i]));
// 将 array 中的元素,以确定的顺序排列
sort(array.begin(), array.end(), compare);
//将 array 中的数字压入到strNUmbers 中
for(int j = 0; j < array.size(); ++j)
strNumbers.append(array[j]);
//返回最小的数
return strNumbers;
}
private:
//比较两个字符串的大小
static bool compare(string strNumbers1, string strNumbers2)
{
//声明一个字符串变量,将 strNumbers1 的元素复制到 Strcombine1 中
string Strcombine1 = strNumbers1;
//将 strNumbers2 的元素连接到 Strcombine1 的尾部
Strcombine1.append(strNumbers2);
//声明一个字符串变量,将 strNumbers2 的元素复制到 Strcombine2 中
string Strcombine2 = strNumbers2;
//将 strNumbers1 的元素连接到 Strcombine2 的尾部
Strcombine2.append(strNumbers1);
//比较 Strcombine1 和 Strcombine2 的大小
return Strcombine1 < Strcombine2;
}
};