1. 程式人生 > >Learning python by leetcode: No.179 Largest number

Learning python by leetcode: No.179 Largest number

contents

題目

179 Largest Number

algorithm

  1. 將int轉化為str;
  2. 排序. 過載比較操作符;
  3. Concatenate list[str] into one str;
  4. Handle the “0” case.

code

class LargeKey(str):
    def __lt__(x,y):
        return x+y < y+x
    
class Solution:
    def largestNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        largest_number= "".join(sorted(map(str,nums), key=LargeKey,
reverse=True)) return "0" if largest_number[0] == '0' else largest_number

details

__lt__()

python3 假定< 和 > 是相反的操作, 如果其中一個沒有定義, 使用另一個的時候就呼叫定義的一個, 只是把對比的物件交換一下位置. 同樣的特性還發生在 <= 和 >= 以及 == 和 !=

map(function, iterable)

Return an iterator that applies function to every item of iterable, yielding the results.

str.join(iterable)

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method

sorted(iterable,*,key=None, reverse=False)

The built-in function sorted() returns a new sorted list from the items in iterable.
Key specifies a function of one argument that is used to extract a comparison key from each element in iterable. The default value is None (compare the elements directly).