179 Largest Number

https://leetcode.com/problems/largest-number/

solution

  • 自定义排序key: 两两比较

import functools

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        def comparator(s1, s2):
            if int(s1+s2) < int(s2+s1):
                return -1
            if int(s1+s2) > int(s2+s1):
                return 1
            return 0

        nums = [str(i) for i in nums]
        nums = sorted(nums, key = functools.cmp_to_key(comparator), reverse=True)
        ans = '0' if nums[0] == '0' else ''.join(nums)
        return ans

时间复杂度:O(sort) 空间复杂度:O(n)

Last updated