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

相关推荐
不会就选b7 小时前
C++补充部分(一)--lambda 表达式
开发语言·c++
罗西的思考13 小时前
【Agentic RL】Dressage Staleness 控制深度分析
人工智能·算法·机器学习
quaer13 小时前
弗洛伊德算法--判圈法寻找环的入口O(n) O(1)
数据结构·算法
丰色木夕14 小时前
Ubuntu22.04下源码编译安装USD-Brep
c++·ubuntu·nvidia·usd-brep
文丑颜不良啊14 小时前
LeetCode51~75题目解析
leetcode
高晶14 小时前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
ysbfsy15 小时前
大数计算思路
算法
高晶15 小时前
主从自动分配算法:平均值乘以设备数一半的选举基准值解析
算法·设计模式·程序员
学电子她就能回来吗15 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
用户老李15 小时前
反向传播计算梯度举例
算法