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

相关推荐
MegaDataFlowers1 天前
1.两数之和
算法
H Journey1 天前
C++ 强制类型转换
c++·类型转换
AGV算法笔记1 天前
二维码检测又卷出新方向:如何在一张图里稳定读取几十甚至上百个二维码?
算法·目标检测·二维码·视觉算法
‎ദ്ദിᵔ.˛.ᵔ₎1 天前
map和set
c++
沐雪轻挽萤1 天前
15. C++17新特性-std::string_view
java·开发语言·c++
sparEE1 天前
进阶排序算法:归并排序
数据结构·算法·排序算法
wearegogog1231 天前
光伏发电系统最大功率跟踪(MPPT)算法 Matlab 实现指南
开发语言·算法·matlab
Tisfy1 天前
LeetCode 3783.整数的镜像距离:数学
数学·算法·leetcode·题解
小小码农Come on1 天前
QML怎么使用C++多线程编程
开发语言·c++
水蓝烟雨1 天前
0010.三数之和
数据结构·算法·leetcode