Topic links: https://leetcode-cn.com/problems/largest-number/
Subject description:
Given a set of non-negative integers, their order rearranged so as to form a largest integer.
Example:
Example 1:
输入: [10,2]
输出: 210
Example 2:
输入: [3,30,34,5,9]
输出: 9534330
Description: The output can be quite large, so you need to return a string instead of an integer.
Ideas:
Custom collations
- use
cmp_to_key
- Magic methods of the class
I can see the details written about Python
ordering summary
n
Array length
k
Number average length of the string
Because of the complexity of sorting time nlogn
Because there is also a comparison between the strings, so the time complexity is \ (knlogn \)
Space complexity: \ (O (n-) \)
Code:
usecmp_to_key
class Solution:
def largestNumber(self, nums: List[int]) -> str:
from functools import cmp_to_key
def helper(x, y):
if x + y > y + x:
return -1
elif x + y < y + x:
return 1
else:
return 0
return "".join(sorted(map(str, nums), key=cmp_to_key(helper))).lstrip("0") or "0"
Magic methods of the class, two ways for writing
A wording:
class Solution:
def largestNumber(self, nums: List[int]) -> str:
class cmp_large:
def __init__(self, num):
self.num = str(num)
def __lt__(self, other):
return self.num + other.num > other.num + self.num
def __gt__(self, other):
return self.num + other.num < other.num + self.num
def __eq__(self, other):
return self.num + other.num == other.num + self.num
nums = [cmp_large(num) for num in nums]
return "".join(a.num for a in sorted(nums)).lstrip("0") or "0"
Written two:
class Solution:
def largestNumber(self, nums: List[int]) -> str:
class large_num(str):
def __lt__(self, other):
return self + other > other + self
return "".join(sorted(map(str, nums), key=large_num)).lstrip("0") or "0"