剑指offer 把数组排成最小的数
问题描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
C++代码实现
思路:1、暴力破解,全排列
2、贪心,自定义排序
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
string ret(numbers.size(), '9');
perm(numbers, 0, ret);
return ret;
}
void perm(vector<int> numbers, int pos, string &ret)
{
if (pos + 1 == numbers.size())
{
string temp = "";
for (int i = 0; i < numbers.size(); i++)
{
temp += to_string(numbers[i]);
}
ret = min(ret, temp);
return;
}
for (int i = pos; i < numbers.size(); i++)
{
swap(numbers[i], numbers[pos]);
perm(numbers, pos+1, ret);
swap(numbers[i], numbers[pos]);
}
}
};
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
vector<string> str;
for (int i = 0; i < numbers.size(); i++)
{
str.push_back(to_string(numbers[i]));
}
sort(str.begin(), str.end(), [](string a, string b){
return a + b < b + a;
});
string ret = "";
for (int i = 0; i < str.size(); i++)
{
ret += str[i];
}
return ret;
}
};
python2代码实现
# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
lmb = lambda n1, n2: int(str(n1) + str(n2)) - int(str(n2) + str(n1))
str_list = sorted(numbers, cmp=lmb)
return ''.join([str(i) for i in str_list])