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

相关推荐
郝学胜-神的一滴4 分钟前
Qt 高级开发 022:栅格布局深度实战
开发语言·c++·qt·软件构建·用户界面
basketball6165 分钟前
设计模式入门:3. 装饰器模式详解 C++实现
c++·设计模式·装饰器模式
菜菜的顾清寒5 分钟前
力扣HOT100(51) 动态规划-单词拆分
算法·leetcode·动态规划
风筝在晴天搁浅14 分钟前
剑指Offer LCR 143.子结构判断
算法
程序大视界17 分钟前
【C++ 从基础到项目实战】C++(三):函数进阶——重载、回调、递归与默认参数
开发语言·c++·cpp
西梅汁21 分钟前
C++ 线程间通信(二)
c++
咖啡八杯23 分钟前
GoF设计模式——装饰模式
java·算法·设计模式·装饰器模式
装不满的克莱因瓶24 分钟前
实现矩阵的点积:从数学原理到 NumPy 实战
人工智能·线性代数·算法·机器学习·矩阵·numpy
HZ·湘怡24 分钟前
树 的定义 与 性质
算法·
minji...24 分钟前
Linux 高级IO(七)多进程、多线程的Reactor反应堆模式扩展、OTOL
linux·运维·c++·多路转接·epoll·reactor反应堆模型