剑指offer-把数组排成最小的数-数组-python
题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
思路1:使用itertools.permutations 函数来进行排列
# -*- coding:utf-8 -*- from itertools import permutations class Solution: def PrintMinNumber(self, numbers): # write code here nums= [] if not numbers: return '' for num in list(permutations(numbers,len(numbers))): numer = ''.join(map(str,num)) nums.append(numer) return min(map(int,nums))
思路二:
使用cmp函数
# -*- coding:utf-8 -*- class Solution: def PrintMinNumber(self, numbers): # write code here return ''.join(sorted([str(i)for i in numbers],self.cmps)) def cmps(self,x,y): return cmp((x+y),(y+x))