题目
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
题目要求
给定一个数组,要求对数组进行重新排列,使得连接起来形成的数字最大。
解题思路
对数组进行排序,比较函数(a,b),比较(a + b)和(b+a)的大小。
同时要注意数组元素都为0的情况
代码
class Solution(object):
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def compare(a,b):
return int(b + a) - int(a + b)
nums = sorted([str(x) for x in nums],cmp = compare)
ans = ''.join(nums).lstrip('0')
return ans or '0'