[leetcode] 179. Largest Number

Description

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"

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

分析

题目的意思是:给你一堆数组,然后把它们排列成一个最大的数。

  • 重写sort函数来排序,然后把排序结果都拼接起来就行了。

代码

class Solution {
public:
    string largestNumber(vector<int>& nums) {
        string res;
        sort(nums.begin(),nums.end(),[](int a,int b){
           return to_string(a)+to_string(b)> to_string(b)+to_string(a); 
        });
        for(int i=0;i<nums.size();i++){
            res+=to_string(nums[i]);
        }
        return res[0]=='0' ? "0":res;
    }
};

代码二 (python)

用python实现了一个版本,在构建排序的时候需要借助functools.cmp_to_key函数

class Solution:
    def largestNumber(self, nums: List[int]) -> str:

        def compare(x, y):
            xy = x+y
            yx = y+x
            if xy>yx:
                return 1
            elif xy<yx:
                return -1
            return 0
        
        num_str = [str(num) for num in nums]
        num_str.sort(key=cmp_to_key(compare),reverse=True)

        largest_num = "".join(num_str)
        if(largest_num[0]=='0'):
            return '0'
        return largest_num

参考文献

[LeetCode] Largest Number 最大组合数

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值