Skip to content

Latest commit

 

History

History
63 lines (45 loc) · 1.96 KB

牛客_0111_中等_最大数.md

File metadata and controls

63 lines (45 loc) · 1.96 KB

最大数

last modify

最大数_牛客题霸_牛客网

问题简述
给定一个长度为n的数组nums,数组由一些非负整数组成,现需要将他们进行排列并拼接,每个数不可拆分,使得最后的结果最大,返回值需要是string类型,否则可能会溢出。
思路
  • 自定义排序,当 int(str(b) + str(a)) > int(str(a) + str(b)) 时,就交换 ab
    • 非 Python 可能存在越界风险;
  • 细节:存在前导 0 的情况;
Python
class Solution:
    def solve(self , nums: List[int]) -> str:
        
        from functools import cmp_to_key
        
        def cmp(a, b):
            # return int(str(b) + str(a)) - int(str(a) + str(b))  # 可能越界
            return 1 if str(b) + str(a) > str(a) + str(b) else -1  # else 0  会出错
        
        nums = sorted(nums, key=cmp_to_key(cmp))
        if nums[0] == 0:
            return '0'
        return ''.join(map(str, nums))