描述
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
Note:
- 1 <= arr.length <= 1000
- -1000 <= arr[i] <= 1000
解析
根据题意,只需要判断 arr 中两种不同的元素出现次数是否有相同即可,利用内置的函数 Counter 来统计每个不同元素的出现次数,然后只需要判断“出现次数”组成的数组中每个元素是否有重复,如果有则为 False ,否则为 True 。
解答
class Solution(object):
def uniqueOccurrences(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
c = collections.Counter(arr)
nums = c.values()
return nums.__len__() == len(set(nums))
运行结果
Runtime: 24 ms, faster than 65.63% of Python online submissions for Unique Number of Occurrences.
Memory Usage: 13.5 MB, less than 53.46% of Python online submissions for Unique Number of Occurrences.
原题链接:leetcode.com/problems/un…
您的支持是我最大的动力