每日一道算法题--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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Head First Mobile Web

Head First Mobile Web

Lyza Danger Gardner、Jason Grigsby / O'Reilly Media / 2011-12 / $ 50.84

Despite the huge number of mobile devices and apps in use today, your business still needs a website. You just need it to be mobile. Head First Mobile Web walks you through the process of making a con......一起来看看 《Head First Mobile Web》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器