剑指offer:把数组排成最小的数

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

# -*- coding: utf-8 -*-
# @Time         : 2019-07-10 19:57
# @Author       : Jayce Wong
# @ProjectName  : job
# @FileName     : printMinNumber.py
# @Blog         : https://blog.51cto.com/jayce1111
# @Github       : https://github.com/SysuJayce

class Solution:
    """
    要求对数组中的数字进行排序,使得排序后的数字最小。
    最朴素的作法就是遍历全部可能的组合,而后选出最小的数字,可是这样作的话要对n!个组合进行比较。

    换个思路,其实这道题就是要对数组中的元素进行一种排序,使得排序后的数组构成最小的数字。
    那么就是须要咱们设计一种比较方式。
    假设数字m和数字n,有两种组合方式mn和nm,注意到mn和nm的长度是同样的,也就是当咱们要比较mn和nm
    的大小的时候,能够直接比较这两个数字的对应位数的数字。因为mn可能超出整型的表示范围,所以咱们需
    要将其转换成字符串的比较,也是只须要比较两个字符串的字典序便可。
    """
    def PrintMinNumber(self, numbers):
        def cmp_to_key(mycmp):
            # 因为在python3中已经移除了多输入的比较函数,在查阅官方文档后发现,排序函数中的比较
            # 函数返回的是一个对象,而不是一个比较的结果,在py3中能够用于选择一个类或者一个多元素
            # 的对象中的一个做为排序的依据。
            # 所以咱们定义一个类,在类中实现比较的函数,而后返回这个类。
            class K:
                def __init__(self, obj):
                    self.obj = obj

                # 通常来说要定义前五个比较函数,最后一个不等于感受意义不大
                def __lt__(self, other):
                    # 须要注意的是这里的other参数也是K类型的,所以咱们要将其obj属性进行对比
                    return mycmp(self.obj, other.obj) < 0

                def __gt__(self, other):
                    return mycmp(self.obj, other.obj) > 0

                def __eq__(self, other):
                    return mycmp(self.obj, other.obj) == 0

                def __le__(self, other):
                    return mycmp(self.obj, other.obj) <= 0

                def __ge__(self, other):
                    return mycmp(self.obj, other.obj) >= 0

                def __ne__(self, other):
                    return mycmp(self.obj, other.obj) != 0

            return K

        # 实际上的比较函数是这个
        def cmp(num1, num2):
            if num1 + num2 > num2 + num1:
                return 1
            elif num1 + num2 == num2 + num1:
                return 0
            else:
                return -1

        if not numbers:
            return ""
        numbers = list(map(str, numbers))
        numbers.sort(key=cmp_to_key(cmp))
        return ''.join(numbers)

def main():
    solution = Solution()
    numbers = [3, 32, 321]
    print(solution.PrintMinNumber(numbers))

if __name__ == '__main__':
    main()
相关文章
相关标签/搜索