目录/Table of Content
1636. Sort Array by Increasing Frequency (按照频率将数组升序排序)
大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄
题目描述
题目描述参考「力扣」中文题目
给你一个整数数组 nums
,现在要按照每个值的频率升序排序。但如果有多个值是相同频率,那就按照数值本身将它们降序排序,然后返回结果数组。
题目原文(英语)
按此进入英语题目链结
Given an array of integers nums
, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.
Return the sorted array.
Example 1:
Input: nums = [1,1,2,2,2,3]
Output: [3,1,1,2,2,2]
Explanation: ‘3’ has a frequency of 1, ‘1’ has a frequency of 2, and ‘2’ has a frequency of 3.
Example 2:
Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
Explanation: ‘2’ and ‘3’ both have a frequency of 2, so they are sorted in decreasing order.
Example 3:
Input: nums = [-1,1,-6,4,5,-6,1,4,1]
Output: [5,-1,4,4,-6,-6,1,1,1]
解题方式
直接用Python內置函數sorted
作二级排序就可以了,需要注意的是因为第二级必须按数值降序排序,所以要用负数-x
。
时间复杂度:O(n l o g log logn)
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
return sorted(nums, key=lambda x: (nums.count(x), -x))