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

相关推荐
逸风尊者34 分钟前
XGBoost模型工程使用
java·后端·算法
小苗卷不动38 分钟前
OJ练习之疯狂的自我检索者(简单)
c++
LUVK_42 分钟前
第七章查找
数据结构·c++·考研·算法·408
迷途之人不知返1 小时前
vector
c++
khalil10201 小时前
代码随想录算法训练营Day-31贪心算法 | 56. 合并区间、738. 单调递增的数字、968. 监控二叉树
数据结构·c++·算法·leetcode·贪心算法·二叉树·递归
小苗卷不动1 小时前
进程与线程的核心区别
c++
lihihi1 小时前
P9936 [NFLSPC #6] 等差数列
算法
啊我不会诶1 小时前
2024ICPC西安邀请赛补题
c++·算法
ZenosDoron1 小时前
keil软件修改字体,Asm editor,和C/C++ editor的区别
c语言·开发语言·c++
山栀shanzhi2 小时前
C/C++之:构造函数为什么不能设置为虚函数?
开发语言·c++·面试