一.问题描述
Given an array of integers arr
, write a function that returns true
if and only if the number of occurrences of each value in the array is unique.
Example 1:
Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
Input: arr = [1,2] Output: false
Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] Output: true
Constraints:
1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000
二.解题思路
很简单的一道题,主要用到哈希,记录每个num的共现次数。之后再通过集合来比较共现次数是否各不相同。
主要就是不要有多余的迭代操作和浪费空间的操作
如果觉得自己对hash这些非常熟悉,不想浪费时间在这道题上,可以直接用python提供的counter类,一行搞定。
Counter类的功能是用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。计数值可以是任意的Interger(包括0和负数)。
demo:
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac
三.代码
给出两个版本:
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
occu={}
for num in arr: # 记录每个num的重现次数
if num not in occu:
occu[num]=1
else:
occu[num]+=1
setocc=set()
for occ_num in occu.values(): #比较是否互不相同
if occ_num in setocc:
return False
else:
setocc.add(occ_num)
return True
一行版
from collections import Counter
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
return tuple(set(Counter(Counter(arr).values()).values())) == (1,)