LeetCode 题解工作台

最大数

给定一组非负整数 nums ,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。 注意: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。 示例 1: 输入 : nums = [10,2] 输出: "210" 示例 2: 输入 : nums = [3,30,34,5,9] 输出:…

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

先转成字符串列表,再对字符串列表进行字典序降序排列。最后将列表所有字符串拼接即可。 class Solution:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。

注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。

 

示例 1:

输入nums = [10,2]
输出:"210"

示例 2:

输入nums = [3,30,34,5,9]
输出:"9534330"

 

提示:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 109
lightbulb

解题思路

方法一:自定义排序

先转成字符串列表,再对字符串列表进行字典序降序排列。最后将列表所有字符串拼接即可。

1
2
3
4
5
6
class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        nums = [str(v) for v in nums]
        nums.sort(key=cmp_to_key(lambda a, b: 1 if a + b < b + a else -1))
        return "0" if nums[0] == "0" else "".join(nums)
speed

复杂度分析

指标
时间O(n \log n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Can the candidate efficiently explain why sorting is key in forming the largest number?

  • question_mark

    Does the candidate address edge cases such as leading zeros or large number sizes?

  • question_mark

    How well does the candidate handle performance considerations when discussing sorting and comparisons?

warning

常见陷阱

外企场景
  • error

    Overlooking the need for a custom sorting function for concatenation comparisons.

  • error

    Failing to handle edge cases, especially when all elements are zeros or very large numbers.

  • error

    Returning an integer instead of a string when the output can be very large.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Use a different sorting method such as a priority queue or bucket sort to optimize performance.

  • arrow_right_alt

    Consider a variation where you need to handle both positive and negative numbers in the input.

  • arrow_right_alt

    Solve the problem while restricting to a certain time complexity or memory limit.

help

常见问题

外企场景

最大数题解:贪心·invariant | LeetCode #179 中等