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

相关推荐
重庆小透明32 分钟前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq1 小时前
力扣:70. 爬楼梯
算法·leetcode·职场和发展
clock的时钟1 小时前
暑期数据结构第一天
数据结构·算法
小小小小王王王2 小时前
求猪肉价格最大值
数据结构·c++·算法
岁忧2 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
BIYing_Aurora2 小时前
【IPMV】图像处理与机器视觉:Lec13 Robust Estimation with RANSAC
图像处理·人工智能·算法·计算机视觉
码农编程录3 小时前
【c/c++3】类和对象,vector容器,类继承和多态,systemd,std&boost
c++
martian6654 小时前
支持向量机(SVM)深度解析:从数学根基到工程实践
算法·机器学习·支持向量机
孟大本事要学习4 小时前
算法19天|回溯算法:理论基础、组合、组合总和Ⅲ、电话号码的字母组合
算法
??tobenewyorker5 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode