32.把数组排成最小的数
问题:
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
解决:
思想:
这道题,我们只需要让,若 a+b<b+a a排在在前 的规则排序,将数组的元素排序,然后拼接起来即可。
python代码:
这里注意一下,因为版本python3中移除了cmp函数,以及sorted函数中的cmp参数,我们需要使用functools中的cmp_to_key来代替原来的cmp参数。
cmp_to_key它有两个传入参数x,y 当x>y时返回1 等于时返回0,否则返回-1
它在list中的工作机制就是将列表中的元素去两两比较,当cmp返回是正数时 交换两元素
# -*- coding:utf-8 -*-
import operator
import functools
class Solution:
def PrintMinNumber(self, numbers):
# write code here
if not numbers:
return ""
lmb=lambda x,y:int(str(x)+str(y))-int(str(y)+str(x))
num=sorted(numbers,key=functools.cmp_to_key(lmb))
return ''.join([str(i) for i in num])