LeetCode Largest Number 贪心

本文详细介绍了如何通过贪心算法将数组元素排列成最大数值,并提供了代码实现。通过对比不同排列组合,证明了贪心策略的有效性,确保数组元素以最大可能的方式组合。

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

将数组中的元素进行重排,组成最大的数。

如果只有两个数,可以简单判断:,使用贪心,将数组中的元素按照上述比较规则进行降序排序,进行拼接即为所求。证明如下:

假设按照贪心得到的最优解为:(其中位,位,)。若存在解(交换位置)比更优。令右边有位,则有:,与假设矛盾。因此贪心为最优解。代码如下:

class Solution {
public:
    string largestNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end(), CMP());
        if(nums[0] == 0)
            return "0";
        string ans = "";
        int len = nums.size();
        for(int i = 0; i < len; ++i){
            ans += to_string(nums[i]);
        }
        return ans;
    }
private:
    struct CMP{
        bool operator()(const int& a, const int& b){
            long long ans1 = 10, ans2 = 10;
            int n1 = a / 10, n2 = b / 10;
            while(n1)
                ans1 *= 10, n1 /= 10;
            while(n2)
                ans2 *= 10, n2 /= 10;
            return ans2 * a + b > ans1 * b + a;
        }
    };
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值