在 Python 中计算列表中存在的元素 x 和 x+1
pythonserver side programmingprogramming更新于 2025/12/25 17:16:17
假设我们有一个名为 nums 的数字列表,我们必须找到元素 x 的数量,使得 x + 1 也存在。
因此,如果输入为 [2, 3, 3, 4, 8],则输出为 3
要解决这个问题,我们将遵循以下步骤 −
- s := 通过插入 nums 中存在的元素来创建一个集合
- count := 0
- 对于 nums 中的每个 i,执行
- 如果 s 中的 i+1,则
- count := count + 1
- 如果 s 中的 i+1,则
- 返回 count
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): s = set(nums) count = 0 for i in nums: if i+1 in s: count += 1 return count ob = Solution() nums = [2, 3, 3, 4, 8] print(ob.solve(nums))
输入
[2, 3, 3, 4, 8]
输出
3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

