【lc刷题】179. Largest Number(sort)

179. Largest Number

Given a list of non-negative integers nums, arrange them such that they form the largest number.
Note: The result may be very large, so you need to return a string instead of an integer.
Example 1:
Input: nums = [10,2]
Output: “210”
Example 2:
Input: nums = [3,30,34,5,9]
Output: “9534330”
Example 3:
Input: nums = [1]
Output: “1”
Example 4:
Input: nums = [10]
Output: “10”
https://leetcode.com/problems/largest-number/

思路:利用built-in sort,写个comparator
譬如
[“12”, “2”] sort完 [“12”,“2”] 也就是122,但212是我们需要的。

也就是sort里面的less than需要变一下,改成a+b > b+a
a=“30”, b=“3”, a+b = “330” > b+a = “303”

不过这次不是直接写function,需要class

注意 edge case:
[0,0] => [“0”,“0”] => “00” 是错的
我们需要返回"0"

class NewKey(str):
    def __lt__(a, b):
        return a+b > b+a

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        nums = map(str, nums)
        res =  "".join(sorted(nums, key=NewKey))
        return "0" if res[0] == "0" else res 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值