| 考点 | 难度 |
|---|---|
| Sorting | Medium |
You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.
Return the string that represents the kth largest integer in nums.
Note: Duplicate numbers should be counted distinctly. For example, if nums is ["1","2","2"], “2” is the first largest integer, “2” is the second-largest integer, and “1” is the third-largest integer.
custom sort: 写一个用来比较strings的function。先比较长短,然后从最左位character开始比较。cmp_to_key( )用来call custom sort的function。
from functools import cmp_to_key
class Solution:
def kthLargestNumber(self, nums: List[str], k: int) -> str:
def sorter(x, y):
n, m = len(x), len(y)
if n < m: # if you want to keep x in left of y, return -1, here if len(x) is shorter, so it is smaller, so left # ['33', '4'], 4 to left
return -1
elif n > m: # +1, if to keep in right of y
return 1
else:
for i in range(n):
if x[i] < y[i]: # if x[i] smaller, then left
return -1
elif x[i] > y[i]: # else in right
return 1
else:
continue
return 0 # if both same, x==y
key = cmp_to_key(sorter)
nums.sort(key=key, reverse=True)
# print(nums)
return nums[k-1]