Leetcode 179.最大数

方法

转换每个整数为字符,然后将字符数组排序。

1
2
3
4
5
6
7
8
9
10
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
nums = map(str,nums)
nums.sort(cmp=lambda a,b: 1 if a+b<b+a else -1)
nums = ''.join(nums)
return '0' if nums[0] == '0' else nums
1
2
3
4
5
6
7
8
9
10
class Solution(object):
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
comp = lambda a,b: 1 if a+b > b+a else -1
nums = map(str, nums)
nums.sort(cmp=comp, reverse=True)
return '0' if nums[0] == '0' else ''.join(nums)
1
2
3
4
5
6
7
class Solution(object):
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
return str(int(''.join(sorted(map(str, nums), cmp=lambda a, b: int(b + a) - int(a + b)))))

理论 Python内置函数

lt(slef,other) 判断self对象是否小于other对象