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

相关推荐
不会就选b20 分钟前
算法日常・每日刷题--<贪心>25
数据结构·算法
蒸蒸yyyyzwd40 分钟前
秋招学习笔记 day46
c++·八股
Cccp.1234 小时前
【leetcode】(七)前缀树和贪心算法
数据结构·leetcode·贪心算法
千里码aicood4 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
码匠许师傅4 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
做cv的小昊4 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له5 小时前
World-In-World: World Models in a Closed-Loop World
算法
无名猿5 小时前
new/delete 与 malloc/free:为什么绝对不能混用
c++·内存管理·现代c++·踩坑记录
2601_962218617 小时前
C++中decltype关键字的实现
开发语言·c++