文章作者:Tyan 博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
解析:这道题的关键在于想到需要编写一个比较函数来比较两个数字的“大小”,即两个数字排列的先后顺序。
- Version 1
import functools
class Solution:
def largestNumber(self, nums):
nums_str = [str(num) for num in nums]
nums_str = sorted(nums_str, key=functools.cmp_to_key(self.compare), reverse=True)
result = ''.join(nums_str)
if result[0] == '0':
return '0'
else:
return result
def compare(self, x, y):
s1 = x y
s2 = y x
if s1 > s2:
return 1
if s1 < s2:
return -1
return 0
- Version 2
import functools
class Solution:
def largestNumber(self, nums):
nums_str = list(map(str, nums))
cmp = lambda x, y: 1 if x y > y x else -1 if x y < y x else 0
nums_str = sorted(nums_str, key=functools.cmp_to_key(cmp), reverse=True)
return str(int(''.join(nums_str)))
Reference
- https://leetcode.com/problems/largest-number/