Learning python by leetcode: No.179 Largest number

版权声明:转载请注明出处. https://blog.csdn.net/laodaliubei/article/details/84034656

题目

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).

猜你喜欢

转载自blog.csdn.net/laodaliubei/article/details/84034656