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

相关推荐
Tandy12356_8 分钟前
手写TCP/IP协议栈——TCP结构定义与基本接口实现
c语言·网络·c++·网络协议·tcp/ip·计算机网络
ghie909011 分钟前
使用直接节点积分法进行无网格法2D悬臂梁计算
算法
Helibo4416 分钟前
2025年12月gesp3级题解
数据结构·c++·算法
p&f°18 分钟前
垃圾回收两种算法
java·jvm·算法
点云SLAM27 分钟前
点云配准算法之- GICP算法点云配准概率模型推导和最大似然求解(MLE)
算法·机器人·slam·点云配准·最大似然估计·点云数据处理·gicp算法
曹轲恒29 分钟前
双栈实现队列/双队列实现栈
算法
西幻凌云35 分钟前
初始——正则表达式
c++·正则表达式·1024程序员节
AI科技星35 分钟前
张祥前统一场论电荷定义方程分析报告
开发语言·经验分享·线性代数·算法·数学建模
Swift社区1 小时前
LeetCode 460 - LFU 缓存
算法·leetcode·缓存
沧澜sincerely1 小时前
蓝桥杯101 拉马车
c++·蓝桥杯·stl