题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
python实现:
class Solution:
def PrintMinNumber2(self, numbers):
# write code here
# 法1:dfs 获得所有排列的可能,取min,时间复杂度大
n = len(numbers)
if n == 0:
return ""
if n == 1:
return str(numbers[0])
cur_min_str = ["".join(map(str, numbers))] # 引用类型
def dfs(numbers, tmp, start, end):
if len(tmp) == n:
cur_min_str[0] = min("".join(map(str, cur_min_str[0])), "".join(map(str, tmp)))
for i in range(start, end+1):
tmp.append(numbers[i])
numbers[i], numbers[start] = numbers[start], numbers[i]
dfs(numbers[:], tmp, start+1, end)
tmp.pop()
dfs(numbers, [], 0, n-1)
return cur_min_str[0]
# 法2:要使得数最小,则应该小数字尽可能靠前,大数字尽可能靠后
# 即其实就是定义一种比较大小的规则,然后按该规则排序(从小到大)
def PrintMinNumber(self, numbers):
n = len(numbers)
if n == 0:
return ""
if n == 1:
return str(numbers[0])
def cmp(a, b): # 例如 4>32
s1, s2 = str(a)+str(b), str(b)+str(a)
if s1>s2:
return 1
elif s1<s2:
return -1
else:
return 0
# import functools
# result = sorted(numbers, key=functools.cmp_to_key(cmp)) # python3
result = sorted(numbers, cmp=cmp) # python2
return "".join(map(str, result))