Python 中的身高检查器
pythonserver side programmingprogramming更新于 2025/11/2 10:52:17
假设一组学生必须按身高不降序排列以拍照。如果我们有一个学生数组,我们必须返回未站在正确位置的最少学生人数。因此,如果数组为 [1, 1, 4, 2, 1, 3],则输出将为 3。因此,身高为 4、3 和最后一个 1 的学生没有站在正确的位置。
为了解决这个问题,我们将遵循以下步骤 −
- answer := 0
- let x := 排序形式的数组
- ley y := 数组
- for i := 0 到数组的大小 – 1 −
- 如果 x[i] 与 y[i] 不同,则将答案增加 1
- 返回 answer
示例
让我们看看下面的实现以便更好地理解 −
class Solution(object): def heightChecker(self, heights): ans = 0 x = sorted(heights) y = heights for i in range(len(x)): if x[i]!=y[i]: ans+=1 return ans ob1 = Solution() print(ob1.heightChecker([1,2,4,2,1,3]))
输入
[1,1,4,2,1,3]
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

