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])