Leetcode刷题记录——179. 最大数

标签: leetcode  python编程技巧

在这里插入图片描述
用一种新规则排序
将int转化为str
若int(str(a[i])+str(a[j]))>int(str(a[j])+str(a[i]))
说明a[i]应放在a[j]前
按这个规则排序
最后累加成字符串即可

注意 若全为0 返回0

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        str_nums = [str(val) for val in nums]
        for i in range(len(nums)-1):
            for j in range(i,len(nums)):
                if int(str_nums[j]+str_nums[i]) > int(str_nums[i]+str_nums[j]):#
                    str_nums[i],str_nums[j] = str_nums[j],str_nums[i]
        print(str_nums)
        if set(str_nums) == {'0'}:
            return '0'
        res = ''
        for each in str_nums:
            res += each
        
        return res


版权声明:本文为weixin_41545780原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_41545780/article/details/107503096