LeetCode 题解工作台
高度检查器
学校打算为全体学生拍一张年度纪念照。根据要求,学生需要按照 非递减 的高度顺序排成一行。 排序后的高度情况用整数数组 expected 表示,其中 expected[i] 是预计排在这一行中第 i 位的学生的高度( 下标从 0 开始 )。 给你一个整数数组 heights ,表示 当前学生站位 的高…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·排序
答案摘要
我们可以先对学生的高度进行排序,然后比较排序后的高度和原始高度,统计不同的位置即可。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 是学生的数量。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
学校打算为全体学生拍一张年度纪念照。根据要求,学生需要按照 非递减 的高度顺序排成一行。
排序后的高度情况用整数数组 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 处的学生高度不匹配。
示例 2:
输入:heights = [5,1,2,3,4] 输出:5 解释: 高度:[5,1,2,3,4] 预期:[1,2,3,4,5] 所有下标的对应学生高度都不匹配。
示例 3:
输入:heights = [1,2,3,4,5] 输出:0 解释: 高度:[1,2,3,4,5] 预期:[1,2,3,4,5] 所有下标的对应学生高度都匹配。
提示:
1 <= heights.length <= 1001 <= heights[i] <= 100
解题思路
方法一:排序
我们可以先对学生的高度进行排序,然后比较排序后的高度和原始高度,统计不同的位置即可。
时间复杂度 ,空间复杂度 。其中 是学生的数量。
class Solution:
def heightChecker(self, heights: List[int]) -> int:
expected = sorted(heights)
return sum(a != b for a, b in zip(heights, expected))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(d * (n + b)) using counting sort where n is the array length and b is the maximum height value. Space complexity is O(n + b) for the copy and frequency counts. |
| 空间 | O(n + b) |
面试官常问的追问
外企场景- question_mark
Expect a solution that leverages sorting for mismatch detection.
- question_mark
Hint towards using counting sort because heights have a small fixed range.
- question_mark
Watch for off-by-one errors when comparing indices between original and sorted arrays.
常见陷阱
外企场景- error
Assuming heights are unique and failing when duplicates exist.
- error
Comparing values incorrectly due to array index mismatch.
- error
Using a slower O(n log n) sort without recognizing counting sort optimization.
进阶变体
外企场景- arrow_right_alt
Return indices of students out of place instead of count.
- arrow_right_alt
Compute minimal swaps required to sort the heights.
- arrow_right_alt
Handle larger ranges of heights efficiently without counting sort.