179. 最大数 - medium
给定一组非负整数 nums
,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。
注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。
示例 1:
输入:
nums = [10,2]
输出:"210"
示例 2:
输入:
nums = [3,30,34,5,9]
输出:"9534330"
示例 3:
输入:
nums = [1]
输出:"1"
示例 4:
输入:
nums = [10]
输出:"10"
提示:
1 <= nums.length <= 100
0 <= nums[i] <= 109
看了题解,证明两个数 x, y 拼接起来时,直接比较 xy
和 yx
谁更大就取对应的排列次序。
import functools
class Solution:
def largestNumber(self, nums: List[int]) -> str:
def cmp(x, y) -> int:
sx, sy = 10, 10
while sx <= x:
sx *= 10
while sy <= y:
sy *= 10
return (sy * x + y) - (sx * y + x)
nums.sort(key=functools.cmp_to_key(cmp), reverse=True)
if nums[0] == 0:
return "0"
return ''.join(str(i) for i in nums)