把数组排成最小的数解题报告

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

第一个偷懒方法,新建一个class重新定义比较函数,然后利用这个class和python自带的sort排序

class new:
    def __init__(self, k):
        self.val = str(k)
    def __lt__(self, other):
        return self.val+other.val < other.val+self.val

class Solution:
        
    def PrintMinNumber(self, numbers):
        # write code here
        ret = []
        for i in numbers:
            ret.append(new(i))
        ret.sort()
        final = "".join(list(map(lambda x:x.val, ret)))
        return final

第二种就是常规解法,自己写一个排序,懒得写了
链接:https://www.nowcoder.com/questionTerminal/8fecd3f8ba334add803bf2a06af1b993?answerType=1&f=discussion
来源:牛客网

class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        length = len(numbers)
        if (length == 0):
            return ''
        str_num = [str(i) for i in numbers]
        for i in range(length-1):
            for j in range(length - i - 1):
                if int(str_num[j]+str_num[j+1]) > int(str_num[j+1]+str_num[j]):
                    str_num[j], str_num[j+1] = str_num[j+1], str_num[j] 
        num = ''.join(i for i in str_num)
        return int(num)

你可能感兴趣的:(把数组排成最小的数解题报告)