[Leetcode] 179. Largest Number @python

本文介绍了一种算法,该算法接收一个非负整数数组,并通过重新排列这些整数以形成可能的最大数字。通过自定义排序函数,比较两个数字连接的不同顺序所形成的数值大小来实现这一目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

题目要求

给定一个数组,要求对数组进行重新排列,使得连接起来形成的数字最大。

解题思路

对数组进行排序,比较函数(a,b),比较(a + b)和(b+a)的大小。
同时要注意数组元素都为0的情况

代码

class Solution(object):
    def largestNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        def compare(a,b):
            return int(b + a) - int(a + b)
        nums = sorted([str(x) for x in nums],cmp = compare)
        ans = ''.join(nums).lstrip('0')

        return ans or '0'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值