


可以通过以下步骤解决这个问题:
-
复制并排序
heights数组得到expected数组。 -
比较
heights和expected,计算它们不同的位置数量。
实现代码如下:
def heightChecker(heights):
expected = sorted(heights) # 排序得到期望的高度顺序
count = sum(heights[i] != expected[i] for i in range(len(heights))) # 计算不匹配的个数
return count
# 测试示例
heights = [1, 1, 4, 2, 1, 3]
print(heightChecker(heights)) # 输出 3
这个代码的时间复杂度是 O(N log N),因为 sorted() 需要 O(N log N) 的时间,而遍历 heights 进行比较需要 O(N) 的时间。
242

被折叠的 条评论
为什么被折叠?



