剑指offer 面试题45 python版+解析:把数组排成最小的数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mabozi08/article/details/88929407

题目描述

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

思路:自己定义一个排序规则,对于字符m,n,如果mn<nm,那么m就排在前面,反之m排在后面。然后调用sort函数即可。

注意python2和python3更改排序规则的代码不一样。

python2: 

# -*- coding:utf-8 -*-
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        if not numbers:
            return ""
        arr = [str(x) for x in numbers]
        arr.sort(lambda x,y:cmp(x+y,y+x))
        return int("".join(arr))

python 3:

# -*- coding:utf-8 -*-
import functools 
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        if not numbers:
            return ""
        arr = list(str(x) for x in numbers)
        def f(a,b):
            if a+b<b+a:
                return -1
            else:
                return 1
        arr.sort(key=functools.cmp_to_key(f))
        return int("".join(arr))

猜你喜欢

转载自blog.csdn.net/mabozi08/article/details/88929407