7/31/2020

[LeetCode] 179. Largest Number

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

Time Complexity : O ( N Log N )

from functools import cmp_to_key
from functools import reduce

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        # a + b > b + a means (a+b) is larger than (b+a) in dictionary order
        dictionaryOrder = cmp_to_key(lambda a, b : 1 if int(a + b) > int(b + a) else -1)
        
        # sort nums in dictionary ascending order
        # concat all numbers from the largest to the smallest. 
        # return 0 if the first digit of final result is '0'
        result = reduce(lambda accumulate, n : accumulate + n, \
                        reversed(sorted(map(str, nums), key = dictionaryOrder)), \
                        '')
           
        return result if result[0] != '0' else '0'

No comments:

Post a Comment