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

相关推荐
KaMeidebaby1 小时前
卡梅德生物技术快报|小 RNA 适配体合成 + 多方法亲和力表征全流程标准化操作手册
前端·网络·数据库·人工智能·算法
是Dream呀1 小时前
基于深度学习的人类行为识别算法研究
人工智能·深度学习·算法
happyprince2 小时前
03_NVIDIA_ModelOpt-量化算法深入
人工智能·深度学习·算法
大鱼>2 小时前
AI+货物追踪:智能快递柜追踪系统
人工智能·深度学习·算法·机器学习
researcher-Jiang3 小时前
算法训练:堆 & 可并堆
算法
郝学胜-神的一滴3 小时前
中级OpenGL教程 013:渲染器类架构设计与逐帧渲染流程详解
开发语言·c++·unity·游戏引擎·图形渲染·opengl·unreal
在书中成长3 小时前
HarmonyOS 小游戏《对战五子棋》开发第18篇 - 棋盘设计
算法·harmonyos
Frostnova丶3 小时前
(12)LeetCode 76. 最小覆盖子串
算法·leetcode·职场和发展
灯澜忆梦3 小时前
GO_函数_1
算法
言乐64 小时前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构