输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
若ab > ba 则 a 大于 b,
若ab < ba 则 a 小于 b,
若ab = ba 则 a 等于 b;
根据上述规则,我们需要先将数字转换成字符串再进行比较,因为需要串起来进行比较。比较完之后,按顺序输出即可。
# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
if len(numbers) == 0:
return ''
compare = lambda a, b:cmp(str(a) + str(b), str(b) + str(a))
min_string = sorted(numbers, cmp = compare)
return ''.join(str(s) for s in min_string)
sort和sorted的区别:
1.sort是list的成员函数,sorted是python内置函数。
2.sort是在原位重新排列列表,而sorted()是产生一个新的列表。
3.sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
python cmp()函数:
cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。
Python3中去除了cmp内置函数,同时sorted等函数也去除了cmp关键字,添加key关键字
py2中sort和sorted的cmp关键字在py3中已经取消了,在py3中要调用该关键字必须要import functools库里面的cmp_to_key。
from functools import cmp_to_key
class Solution:
def cmp(self,a,b):
if a+b>b+a:
return 1
if a+b<b+a:
return -1
else:
return 0
def PrintMinNumber(self,numbers):
if not numbers:
return ""
number = list(map(str,numbers))
number.sort(key=cmp_to_key(self.cmp))
return "".join(number).lstrip('0') or '0'
so = Solution()
so.PrintMinNumber([3,32,321])