用 Python 检查每个值的出现次数是否唯一的程序

pythonserver side programmingprogramming更新于 2026/2/4 18:52:17

假设我们有一个数字列表 nums(正数或负数),我们必须检查数组中每个值的出现次数是否唯一。

因此,如果输入为 nums = [6, 4, 2, 9, 4, 2, 2, 9, 9, 9],则输出将为 True,因为 6 出现 1 次,4 出现 2 次,2 出现 3 次,9 出现 4 次。因此所有出现次数都是唯一的。

为了解决这个问题,我们将遵循以下步骤 −

  • num_counts := 一个新的映射,其中存储了所有值和该值的出现次数

  • occurrences := 所有值的列表num_counts 的值

  • 当出现次数的大小与出现次数中唯一元素的数量相同时返回 True,否则返回 false

让我们看看下面的实现以便更好地理解 −

示例

from collections import Counter
class Solution:
   def solve(self, nums):
      num_counts = dict(Counter(nums))
      occurrences = num_counts.values()
      return len(occurrences) == len(set(occurrences))
ob = Solution()
nums = [6, 4, 2, 9, 4, 2, 2, 9, 9, 9]
print(ob.solve(nums))

输入

[6, 4, 2, 9, 4, 2, 2, 9, 9, 9]

输出

True

相关文章


有用资源