2022.9.19的每日一题,这个题主要是需要对数组排序时使用second key,并且first key是升序但是second key是倒序。主要的思路就是先用一个字典记录num对应的出现频率,即num_frequency = {num: frequency},然后对这个字典进行排序,first key是frequency(升序),second key是num大小,但是是倒序,因为都是数值,因此可以直接把second key改为-num,升序即可。
num_frequency = sorted(num_frequency.items(), key=lambda x: (x[1], -x[0]))
完整代码如下:
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
num_frequency = {}
for num in nums:
if num in num_frequency.keys():
num_frequency[num] += 1
else:
num_frequency[num] = 1
num_frequency = sorted(num_frequency.items(), key=lambda x: (x[1], -x[0]))
res = []
for num, frequency in num_frequency:
for i in range(frequency):
res.append(num)
return res
好的,看了一下官方题解,好简洁,我真的栓Q:
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
cnt = Counter(nums)
nums.sort(key=lambda x: (cnt[x], -x))
return nums
学习了,还可以用Counter呢,牛逼。