''' 题目描述 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。 例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。 ''' class Solution: def self_cmp(self,x,y): ''' :param x: str type :param y: str type :return: python中的sorted函数中的cmp关键字,采用的是python自带的cmp函数, 而这个参数在sorted函数中可以由用户指定,只需要满足: 当x>y 时,返回1 当x<y 时,返回-1 当x=y 时,返回0 ''' if x+y>y+x:# 说明应该x较大 return 1 elif x+y<y+x: return -1 else: return 0 def PrintMinNumber(self, numbers): # write code here if not numbers: return '' numbers=list(map(str,numbers)) numbers.sort(cmp=self.self_cmp) output='' for elem in numbers: output+=elem return int(output)
剑指offer 把数组排成最小的数
最新推荐文章于 2022-05-16 17:32:46 发布