用 Python 编写程序,查找排序列表中唯一整数的数量

pythonserver side programmingprogramming更新于 2026/1/8 16:44:17

假设我们有一个名为 nums 的排序数字列表,我们必须找到列表中唯一元素的数量。

因此,如果输入为 nums = [3, 3, 3, 4, 5, 7, 7],则输出为 4,因为唯一数字为 [3, 4, 5, 7]

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

  • s:= 一个新集合
  • cnt:= 0
  • 对于 nums 中的每个 i,执行
    • 如果 i 不在 s 中,则
      • 将 i 插入 s
      • cnt := cnt + 1
  • 返回 cnt

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

示例

class Solution:
   def solve(self, nums):
      s=set()
      cnt=0
      for i in nums:
         if i not in s:
            s.add(i)
            cnt += 1
      return cnt
ob = Solution()
print(ob.solve([3, 3, 3, 4, 5, 7, 7]))

输入

[3, 3, 3, 4, 5, 7, 7]

输出

4

相关文章


有用资源