每日一道算法题--leetcode 179--最大数--python

栏目: Python · 发布时间: 6年前

内容简介:第一反应是用冒泡排序,但是时间复杂度比较高,所以采用了python库函数简化代码。其实这道题就是要对比int(str(nums[i])+str(nums[i+1])) 和 int(str(nums[i+1])+str(nums[i]))究竟谁比较大,然后将较大的放在数组的前面,也就是逆序排列。 使用python中的sorted函数,使用key这个参数,用下面这个作为key,然后对key进行排序,再用reverse参数做逆序

【题目描述】

每日一道算法题--leetcode 179--最大数--python
【代码思路】

第一反应是用冒泡排序,但是时间复杂度比较高,所以采用了 python 库函数简化代码。其实这道题就是要对比

int(str(nums[i])+str(nums[i+1])) 和 int(str(nums[i+1])+str(nums[i]))

究竟谁比较大,然后将较大的放在数组的前面,也就是逆序排列。 使用python中的sorted函数,使用key这个参数,用下面这个作为key,然后对key进行排序,再用reverse参数做逆序

key=cmp_to_key(lambda x,y:int(x+y)-int(y+x))
复制代码

关于cmp_to_key函数的解析见这篇文章 一句话理解cmp_to_key函数

【源代码】

调用库函数的方法:
class Solution(object):
    def largestNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        from functools import cmp_to_key 
        nums=sorted([str(i) for i in nums],key=cmp_to_key(lambda x,y:int(x+y)-int(y+x)),reverse=True)
        if int(''.join(nums))==0:return '0'
        else: return ''.join(nums)
复制代码
冒泡排序:
class Solution(object):
    def largestNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        for i in range(len(nums)-1):
            for j in range(i+1,len(nums)):
                if int(str(nums[i])+str(nums[j]))-int(str(nums[j])+str(nums[i]))<0:
                    temp=nums[i]
                    nums[i]=nums[j]
                    nums[j]=temp
        nums=[str(i) for i in nums]
        if int(''.join(nums))==0:return '0'
        else:return ''.join(nums)
复制代码

以上所述就是小编给大家介绍的《每日一道算法题--leetcode 179--最大数--python》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms to Live By

Algorithms to Live By

Brian Christian、Tom Griffiths / Henry Holt and Co. / 2016-4-19 / USD 30.00

A fascinating exploration of how insights from computer algorithms can be applied to our everyday lives, helping to solve common decision-making problems and illuminate the workings of the human mind ......一起来看看 《Algorithms to Live By》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

html转js在线工具
html转js在线工具

html转js在线工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具