LeetCode 题解工作台

独一无二的出现次数

给你一个整数数组 arr ,如果每个数的出现次数都是独一无二的,就返回 true ;否则返回 false 。 示例 1: 输入: arr = [1,2,2,1,1,3] 输出: true 解释: 在该数组中,1 出现了 3 次,2 出现了 2 次,3 只出现了 1 次。没有两个数的出现次数相同。 示…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们用哈希表 统计数组 中每个数的出现次数,然后用哈希表 统计出现次数的种类,最后判断 和 的大小是否相等即可。 时间复杂度 ,空间复杂度 。其中 为数组 的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 arr,如果每个数的出现次数都是独一无二的,就返回 true;否则返回 false

 

示例 1:

输入:arr = [1,2,2,1,1,3]
输出:true
解释:在该数组中,1 出现了 3 次,2 出现了 2 次,3 只出现了 1 次。没有两个数的出现次数相同。

示例 2:

输入:arr = [1,2]
输出:false

示例 3:

输入:arr = [-3,0,1,-3,1,1,1,-3,10,0]
输出:true

 

提示:

  • 1 <= arr.length <= 1000
  • -1000 <= arr[i] <= 1000
lightbulb

解题思路

方法一:哈希表

我们用哈希表 cntcnt 统计数组 arrarr 中每个数的出现次数,然后用哈希表 visvis 统计出现次数的种类,最后判断 cntcntvisvis 的大小是否相等即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 arrarr 的长度。

1
2
3
4
5
class Solution:
    def uniqueOccurrences(self, arr: List[int]) -> bool:
        cnt = Counter(arr)
        return len(set(cnt.values())) == len(cnt)
speed

复杂度分析

指标
时间complexity is O(n) for a single pass through the array to build the hash map plus O(n) to check uniqueness, yielding O(n) overall. Space complexity is O(n) for storing counts in the hash map and potentially O(n) for the set storing unique frequencies.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Can you implement this in one pass for counting and a second pass for uniqueness checking?

  • question_mark

    What happens if the array contains negative numbers or zeros?

  • question_mark

    How would your solution change if the array size increased to millions of elements?

warning

常见陷阱

外企场景
  • error

    Forgetting to handle negative numbers correctly in the hash map.

  • error

    Checking counts in-place instead of using a separate set, leading to false positives.

  • error

    Assuming sorted arrays or consecutive numbers, which is not required.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check if occurrences are unique but allow at most two numbers to share the same count.

  • arrow_right_alt

    Determine unique occurrences without using extra space, modifying the input array.

  • arrow_right_alt

    Return the list of numbers that violate unique occurrence rules instead of just true/false.

help

常见问题

外企场景

独一无二的出现次数题解:数组·哈希·扫描 | LeetCode #1207 简单