Re: [闲聊] 每日leetcode

楼主: JerryChungYC (JerryChung)   2024-07-23 09:06:49
https://leetcode.com/problems/sort-array-by-increasing-frequency
1636. Sort Array by Increasing Frequency
给一个整数数组 nums ,依照值出现的频率进行升序排序
如果多个值有相同的频率,则这些值按降序进行排序
Example 1:
Input: nums = [1,1,2,2,2,3]
Output: [3,1,1,2,2,2]
Example 2:
Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
Explanation: 2跟3的频率相同,降序为3>2
Example 3:
Input: nums = [-1,1,-6,4,5,-6,1,4,1]
Output: [5,-1,4,4,-6,-6,1,1,1]
思路:
先计算出频率,排序后再根据次数重复放入
Python Code:
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
result = []
for key, count in sorted(Counter(nums).items(), key=lambda x: (x[1], -x[0])):
result.extend([key] * count)
return result
因为相同频率要降序 所以用(x[1], -x[0])
楼主: JerryChungYC (JerryChung)   2024-07-23 09:11:00
喔排序用原nums Counter拿来当key就好
作者: sustainer123 (caster)   2024-07-23 09:17:00
大师
作者: DJYOMIYAHINA (通通打死)   2024-07-23 09:18:00
放过我放过我放过我放过我放过我

Links booklink

Contact Us: admin [ a t ] ucptt.com