两个数字对应的字符串 a 和 b,如果字典序 a+b > b+a,此时 a 排在 b 的前面即可获得更大值
示例:a = 3, b = 32,两者拼接的值:332 > 323,所以 3 应排在 3 2前面
class Solution:
def largestNumber(self, nums: List[int]) -> str:
n=len(nums)
nums=list(map(str,nums))
for i in range(n):
for j in range(i+1,n):
if nums[i]+nums[j] < nums[j]+nums[i]:
nums[i],nums[j] = nums[j],nums[i]
return str(int("".join(nums)))
方法二:cmp_to_key
利用 cmp_to_key 函数,传入两个参数(x, y)对应于(self, other),这里的 self 表示当前的数,而 other 是前面已经出现比较过的对象。比如 arr = [3, 32],此时 self 为 32,other 为 3,即 x = 32, y = 3,这里与惯性思维是相反的.
示例:x = 32, y = 3,或者说 y 为数组前面的数,x 为数组后面的数。要使得构造的数更大,需要满足条件:前面的数 + 后面的数 > 后面的数 + 前面的数,即 y + x > x + y 返回 1 成立,即 332 > 323 成立,此时 3 出现在 32 前面
class Solution:
def largestNumber(self, nums: List[int]) -> str:
def cmp(x,y): return 1 if x+y
class Solution:
def largestNumber(self, nums: List[int]) -> str:
'''
nums = map(str, nums)
# x = sorted(nums, key=cmp_to_key(lambda x, y:1 if x+y >= y+x else -1), reverse=True)
x = sorted(nums, key=cmp_to_key(lambda x, y:int(x+y)-int(y+x)), reverse=True)
return ''.join(x) if x[0] != '0' else '0'
'''
ret = ''
n = len(nums)
s = map(str, nums)
s = sorted(s, reverse=True)
for i in range(n-1):
for j in range(i+1, n):
if int(s[i] + s[j]) < int(s[j] + s[i]):
s[i], s[j] = s[j], s[i]
ret += s[i]
ret += s[-1]
return ret[0] if int(ret) == 0 else ret
'''
#from functools import cmp_to_key
ret = map(str, nums)
def cmp(a, b):
if a + b >= b + a:
return 1
else:
return -1
ret = sorted(ret, key=cmp_to_key(cmp), reverse=True)
return ''.join(ret) if ret[0] != '0' else '0'
'''



