栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python Leetcode

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python Leetcode

179. 最大数 方法一:排序

两个数字对应的字符串 a 和 b,如果字典序 a+b > b+a,此时 a 排在 b 的前面即可获得更大值
示例:a = 3, b = 32,两者拼接的值:332 > 323,所以 3 应排在 3 2前面

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        n=len(nums)
        nums=list(map(str,nums))
        for i in range(n):
            for j in range(i+1,n):
                if nums[i]+nums[j] < nums[j]+nums[i]:
                    nums[i],nums[j] = nums[j],nums[i]
        
        return str(int("".join(nums)))

方法二:cmp_to_key

利用 cmp_to_key 函数,传入两个参数(x, y)对应于(self, other),这里的 self 表示当前的数,而 other 是前面已经出现比较过的对象。比如 arr = [3, 32],此时 self 为 32,other 为 3,即 x = 32, y = 3,这里与惯性思维是相反的.
示例:x = 32, y = 3,或者说 y 为数组前面的数,x 为数组后面的数。要使得构造的数更大,需要满足条件:前面的数 + 后面的数 > 后面的数 + 前面的数,即 y + x > x + y 返回 1 成立,即 332 > 323 成立,此时 3 出现在 32 前面

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        def cmp(x,y): return 1 if x+y 
class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        '''
        nums = map(str, nums)
        # x = sorted(nums, key=cmp_to_key(lambda x, y:1 if x+y >= y+x else -1), reverse=True)
        x = sorted(nums, key=cmp_to_key(lambda x, y:int(x+y)-int(y+x)), reverse=True)
        return ''.join(x) if x[0] != '0' else '0'

        '''
        ret = ''
        n = len(nums)
        s = map(str, nums)
        s = sorted(s, reverse=True)
        for i in range(n-1):
            for j in range(i+1, n):
                if int(s[i] + s[j]) < int(s[j] + s[i]):
                    s[i], s[j] = s[j], s[i]
            ret += s[i]
        ret += s[-1]
        return ret[0] if int(ret) == 0 else ret
        '''    
               
        #from functools import cmp_to_key

        ret = map(str, nums)

        def cmp(a, b):
            if a + b >= b + a:
                return 1
            else:
                return -1
                
        ret = sorted(ret, key=cmp_to_key(cmp), reverse=True)
        return ''.join(ret) if ret[0] != '0' else '0'
        '''
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/314044.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号