LeetCode179. Largest Number(思路及python解法)

173 篇文章 0 订阅

Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

Input: [10,2]

Output: "210"

Example 2:

Input: [3,30,34,5,9]

Output: "9534330"

将数组中的数组合成一个新的数,使新的数最大。

一开始没什么思路,看了discuss才想明白。

其实关键在于如何排序,也就是compare这个函数将两个数进行排序。比如[10,2],组合就是“102”和“210”两种。

按照这个思路把整个数组重新排序一遍即可。为了避免多个0在一起,如果第一个字符为0则直接返回0。

至于两个for循环就是一个冒泡排序方法,用什么排序都可以。

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        
        for i in range(len(nums)):
            for j in range(len(nums)-i-1):
                if self.compare(nums[j+1],nums[j]):
                    nums[j], nums[j+1] = nums[j+1], nums[j]
        res=''.join(map(str,nums))
        return '0' if res[0]=='0' else res
            
    def compare(self, n1, n2):
        return str(n1)+str(n2)>str(n2)+str(n1)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值