题目
学校打算为全体学生拍一张年度纪念照。根据要求,学生需要按照 非递减 的高度顺序排成一行。
排序后的高度情况用整数数组 expected 表示,其中 expected[i] 是预计排在这一行中第 i 位的学生的高度(下标从 0 开始)。
给你一个整数数组 heights ,表示 当前学生站位 的高度情况。heights[i] 是这一行中第 i 位学生的高度(下标从 0 开始)。
返回满足 heights[i] != expected[i] 的 下标数量 。
示例:
输入:heights = [1,1,4,2,1,3]
输出:3
解释:
高度:[1,1,4,2,1,3]
预期:[1,1,1,2,3,4]
下标 2 、4 、5 处的学生高度不匹配。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/height-checker
思路
计数排序:先求出必要长度--遍历并且标记index--遍历得到排序后的结果
代码
class Solution:
def heightChecker(self, heights: List[int]) -> int:
# 首先找到最大值
ceiling = max(heights)
back = [0 for i in range(1+ceiling)]
# 然后遍历,标记次数
for index in heights:
back[index] = back[index] + 1
# 得到排序后的结果
res = []
for i, count in enumerate(back):
if count > 0:
for j in range(count):
res.append(i)
# 求出diff个数
inverseCount = 0
for i in range(len(heights)):
if heights[i] != res[i]:
inverseCount += 1
return inverseCount