版权声明:转载请注明出处. https://blog.csdn.net/laodaliubei/article/details/84034656
contents
题目
algorithm
- 将int转化为str;
- 排序. 重载比较操作符;
- Concatenate list[str] into one str;
- 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).