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

相关推荐
ZC跨境爬虫8 分钟前
LeetCode 219. 存在重复元素 II(滑动窗口 + 哈希表详解)
算法·leetcode·散列表
zh路西法12 分钟前
【玩转VLA具身智能机械臂】(三):视觉避障——从 RGB-D 点云到 MoveIt octomap 的完整落地
c++·ros2·gazebo·moveit2·ompl·octomap
吞下星星的少年·-·17 分钟前
The 2025 ICPC Asia East Continent Online Contest (I) A题(模拟+贪心)
算法·贪心·模拟
小程序设计37 分钟前
【机械设计】磁粉检测机器人的设计与验证
算法·机器人
Navigator_Z43 分钟前
LeetCode //C - 1220. Count Vowels Permutation
c语言·算法·leetcode
吃好睡好便好1 小时前
判断函数的使用
学习·算法·matlab·生活·判断函数
2601_956121971 小时前
线性DP(入门)
c++·算法·动态规划
彷徨而立1 小时前
【C/C++】多线程读写普通 int 变量的一些问题
java·c语言·c++
feilieren1 小时前
leetcode - 389. 找不同
算法·leetcode
挽星安1 小时前
2026/8/29
数据结构·算法