Algorithm
本周选择的算法题是:Largest Number。
规则
Given a list of non-negative integers nums
, arrange them such that they form the largest number.
Note: The result may be very large, so you need to return a string instead of an integer.
Example 1:
Input: nums = [10,2]
Output: "210"
Example 2:
Input: nums = [3,30,34,5,9]
Output: "9534330"
Example 3:
Input: nums = [1]
Output: "1"
Example 4:
Input: nums = [10]
Output: "10"
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 109
Solution
class Solution:
def largestNumber(self, nums: List[int]) -> str:
def comparator(num1, num2):
int1, int2 = int(num1 + num2), int(num2 + num1)
if int1 > int2:
return 1
elif int1 < int2:
return -1
else:
return 0
nums = [str(num) for num in nums]
nums = sorted(nums, key=cmp_to_key(comparator), reverse=True)
return '0' if nums[0] == '0' else "".join(nums)
Review
Python — From Intermediate to Superhero
这篇文章列出了很多 Python 语言的特性,但更重要的是作者对这些特性背后的理解和洞见,对于那些不希望只停留在语法学习上的人来说,这篇文章还是值得一读的。
Tip
- 优化搜索样式,同时增加了对 Dark 的支持。