largest number - leetcode - python

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.


题意: 给出一个数字组成的数组list,要求得出由各个数字拼接成的最大数字。
重写sort内置的比较方法即可,将两个数字进行比较,首先两个数字转换成字符串拼接起来,比较a+b, b+a 哪一个的数值大,然后返回递减序列。
在python中有a.sort() 和 sorted()方法,在这里则是将sorted中的 cmp重写,创建了一个自定义的strcmp函数,对数字进行比较

class Solution:
    # @param {integer[]} nums
    # @return {string}
 
    def largestNumber(self, nums):
        def strcmp(a,b):  # if aba:
                return -1
            else:
                return 0 
        
        res = sorted(nums,cmp=strcmp)
        num = len(res)
        if res[0]==0:
            return str(0)
        temp = str(res[0])
        i = 1
        while i

你可能感兴趣的:(LeetCode)