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)。

相关推荐
持梦远方2 小时前
【C++日志库】启程者团队开源:轻量级高性能VoyLog日志库完全指南
开发语言·c++·visual studio
mit6.8242 小时前
博弈dp|凸包|math分类
算法
许长安2 小时前
C++中指针和引用的区别
c++·经验分享·笔记
Shinom1ya_2 小时前
算法 day 41
数据结构·算法·leetcode
hetao17338372 小时前
2025-10-30 ZYZOJ Star(斯达)模拟赛 hetao1733837的record
c++·算法
无敌最俊朗@2 小时前
C++ 值类别与移动语义详解(精简版)
java·数据结构·算法
lingran__3 小时前
算法沉淀第十一天(序列异或)
c++·算法
一匹电信狗3 小时前
【C++】红黑树详解(2w字详解)
服务器·c++·算法·leetcode·小程序·stl·visual studio
散峰而望3 小时前
Dev-C++一些问题的处理
c语言·开发语言·数据库·c++·编辑器
进击的大海贼4 小时前
QT/C++ 消息定时管理器
开发语言·c++·qt