用 Python 编写程序来计算放置在正确位置的元素数量
pythonserver side programmingprogramming更新于 2026/1/6 23:40:17
假设我们有一个名为 nums 的数字列表,当列表要排序时,我们必须找到正确索引中存在的元素数量。
因此,如果输入为 [2, 8, 4, 5, 11],则输出将为 2,因为元素 2 和 11 位于正确的位置。排序后的序列将是 [2, 4, 5, 8, 11]
为了解决这个问题,我们将遵循以下步骤 −
- s := 对列表 nums 进行排序
- count := 0
- 对于 i,范围从 0 到 nums 的大小,执行
- 如果 s[i] 与 nums[i] 相同,则
- count := count + 1
- 如果 s[i] 与 nums[i] 相同,则
- 返回 count
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): s = sorted(nums) count = 0 for i in range(len(nums)): if s[i] == nums[i]: count += 1 return count ob = Solution() print(ob.solve([2, 8, 4, 5, 11]))
输入
[2, 8, 4, 5, 11]
输出
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

