把数组排列成最小的数-python

题目描述

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

思路

制定一个排序规则,如果a和b两个数字组合ab>ba,则a、b调换顺序,否则不调

class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        if len(numbers)==0:
            return ''
        def camp(a,b):
            if int(str(a)+str(b))<int(str(b)+str(a)):
                return -1
            elif int(str(a)+str(b))>int(str(b)+str(a)):
                return 1
            else:
                return 0
        tmpNumbers = sorted(numbers,cmp=camp)
        return int(''.join(str(i) for i in tmpNumbers))

python2中

sort()和sorted()函数有一个cmp函数,用来定制化排序的比较方法。cmp取值[-1,1,0],分别表示a的逻辑比b小、大、相等

python3中

sort()和sorted()除去的cmp 参数,推荐使用 key

import functools
def tcmp(a,b):
	if a > b :
		return -1
	elif a < b :
		return 1
	else:
		return 0
		
nums = [1,2,3,4]
sorted_nums = sorted(nums, key = functools.cmp_to_key(tcmp))
发布了26 篇原创文章 · 获赞 12 · 访问量 2946

猜你喜欢

转载自blog.csdn.net/m0_38126296/article/details/90453169