Tuesday, March 5, 2019

LeetCode 179. Largest Number

'''
Given a list of non negative integers, arrange them such that they form the largest number.

'''

'''
learned:
the use of build-in function sorted() including order and key
the customization of __lt__
'''

class cf(str):
    def __lt__(a, b):
        return a+b < b+a

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        strs = [str(i) for i in nums]
        result = ''.join(sorted(strs, reverse=True, key=cf))
        if result[0] == '0':
            return '0'
        else:
            return result
       

No comments:

Post a Comment