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