LeetCode 题解工作台

按照频率将数组升序排序

给你一个整数数组 nums ,请你将数组按照每个值的频率 升序 排序。如果有多个值的频率相同,请你按照数值本身将它们 降序 排序。 请你返回排序后的数组。 示例 1: 输入: nums = [1,1,2,2,2,3] 输出: [3,1,1,2,2,2] 解释: '3' 频率为 1,'1' 频率为 2…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

用数组或者哈希表统计 `nums` 中每个数字出现的次数,由于题目中数字的范围是 $[-100, 100]$,我们可以直接创建一个大小为 的数组来统计。 然后对 `nums` 按照数字出现次数升序排序,如果出现次数相同,则按照数字降序排序。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,请你将数组按照每个值的频率 升序 排序。如果有多个值的频率相同,请你按照数值本身将它们 降序 排序。 

请你返回排序后的数组。

 

示例 1:

输入:nums = [1,1,2,2,2,3]
输出:[3,1,1,2,2,2]
解释:'3' 频率为 1,'1' 频率为 2,'2' 频率为 3 。

示例 2:

输入:nums = [2,3,1,3,2]
输出:[1,3,3,2,2]
解释:'2' 和 '3' 频率都为 2 ,所以它们之间按照数值本身降序排序。

示例 3:

输入:nums = [-1,1,-6,4,5,-6,1,4,1]
输出:[5,-1,4,4,-6,-6,1,1,1]

 

提示:

  • 1 <= nums.length <= 100
  • -100 <= nums[i] <= 100
lightbulb

解题思路

方法一:数组或哈希表计数

用数组或者哈希表统计 nums 中每个数字出现的次数,由于题目中数字的范围是 [100,100][-100, 100],我们可以直接创建一个大小为 201201 的数组来统计。

然后对 nums 按照数字出现次数升序排序,如果出现次数相同,则按照数字降序排序。

时间复杂度为 O(n×logn)O(n \times \log n),空间复杂度 O(n)O(n)。其中 nn 为数组 nums 的长度。

1
2
3
4
5
class Solution:
    def frequencySort(self, nums: List[int]) -> List[int]:
        cnt = Counter(nums)
        return sorted(nums, key=lambda x: (cnt[x], -x))
speed

复杂度分析

指标
时间complexity is O(N log N) due to sorting the array, and space complexity is O(N) for storing frequency counts in a hash map.
空间O(N)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for clear separation between counting and sorting steps.

  • question_mark

    Watch for proper tie-breaking by descending value when frequencies match.

  • question_mark

    Ensure the solution scales within the 100-element constraint efficiently.

warning

常见陷阱

外企场景
  • error

    Sorting only by frequency and ignoring descending value tie-breaking.

  • error

    Using nested loops instead of a hash map for frequency counting.

  • error

    Mutating the input array unnecessarily, causing side effects.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Sort array by decreasing frequency with ascending value ties.

  • arrow_right_alt

    Return only the top k frequent elements in sorted order.

  • arrow_right_alt

    Handle very large arrays where counts exceed integer limits.

help

常见问题

外企场景

按照频率将数组升序排序题解:数组·哈希·扫描 | LeetCode #1636 简单