社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

杉杉不要bug • 6 年前 • 512 次点击  
阅读 10

每日一道算法题--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)
复制代码
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/32535
 
512 次点击