美文网首页
LeetCode 1207. Unique Number of

LeetCode 1207. Unique Number of

作者: LiNGYu_NiverSe | 来源:发表于2020-11-24 00:13 被阅读0次

    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

    Solution

    from collections import Counter
    class Solution:
        def uniqueOccurrences(self, arr: List[int]) -> bool:
            lookup = Counter(arr)
            set_a = set(arr)
            return len(set_a) == len(set(lookup.values()))
    

    The idea is to count the number of occurrence of each element in arr and get the unique count of each number. Then we compare it with the number of unique elements. If they are the same, then it means each element has unique counts. Otherwise, we return False.
    本题思路是计算arr中每个元素的出现次数,并获得每个数字的唯一计数。然后,我们将其与唯一元素的数量进行比较。如果它们相同,则意味着每个元素都有唯一的计数。否则,我们返回False。

    相关文章

      网友评论

          本文标题:LeetCode 1207. Unique Number of

          本文链接:https://www.haomeiwen.com/subject/ycvbiktx.html