Leetcode179. 最大数

Every day a Leetcode

题目来源:179. 最大数

解法1:贪心

对于数组 nums 中的任意两个数 a 和 b,我们将其转换为字符串后,如果 to_string(a) + to_string(b) > to_string(b) + to_string(a),说明 a 应该放在 b 的前面,这样拼接成的数字更大。

注意特判全为 0 的情况,这样会拼接出类似于 "0...00" 的字符串,应该只返回 "0"。

代码:

c 复制代码
/*
 * @lc app=leetcode.cn id=179 lang=cpp
 *
 * [179] 最大数
 */

// @lc code=start
class Solution
{
private:
    static bool cmp(const int &a, const int &b)
    {
        return to_string(a) + to_string(b) > to_string(b) + to_string(a);
    }

public:
    string largestNumber(vector<int> &nums)
    {
        int n = nums.size();
        sort(nums.begin(), nums.end(), cmp);
        string ans;
        for (const int &num : nums)
            ans += to_string(num);
        return ans[0] == '0' ? "0" : ans;
    }
};
// @lc code=end

结果:

复杂度分析:

时间复杂度:O(nlogn),其中 n 是数字 nums 的元素个数。

空间复杂度:O(1)。

相关推荐
小雅痞6 分钟前
[Java][Leetcode simple] 1. 两数之和
java·算法·leetcode
somi710 分钟前
ARM-驱动-09-LCD FrameBuffer
arm开发·驱动开发·算法·自用
乐迪信息11 分钟前
乐迪信息:智慧港口AI防爆摄像机实现船舶违规靠岸自动抓拍
大数据·人工智能·算法·安全·目标跟踪
winxp-pic14 分钟前
图片校正软件 操作说明及算法介绍
算法
wayz1120 分钟前
Day 6 编程实战:决策树与过拟合分析
算法·决策树·机器学习
ฅ ฅBonnie28 分钟前
vLLM 推理后端简介
人工智能·python·算法
历程里程碑29 分钟前
Linux 50 IP协议深度解析:从报头结构到子网划分与NAT
java·linux·开发语言·网络·c++·python·智能路由器
贾斯汀玛尔斯29 分钟前
每天学一个算法--堆排序(Heap Sort)
数据结构·算法
programhelp_31 分钟前
ZipRecruiter CodeSignal OA 2026|最新真题分享 + 速通攻略
数据结构·经验分享·算法·面试
犹怜草木青1 小时前
const关键字
c++