LeetCode1051. 高度检查器
题目描述
本题目来自LeetCode上的『1051. 高度检查器』
学校打算为全体学生拍一张年度纪念照。根据要求,学生需要按照 非递减 的高度顺序排成一行。
排序后的高度情况用整数数组 expected
表示,其中 expected[i]
是预计排在这一行中第 i
位的学生的高度(下标从 0 开始)。
给你一个整数数组 heights
,表示 当前学生站位 的高度情况。heights[i]
是这一行中第 i
位学生的高度(下标从 0 开始)。
返回满足 heights[i] != expected[i]
的 下标数量 。
示例1:
输入:heights = [1,1,4,2,1,3]
输出:3
解释:
高度:[1,1,4,2,1,3]
预期:[1,1,1,2,3,4]
下标 2 、4 、5 处的学生高度不匹配。
提示
1 <= heights.length <= 100
1 <= heights[i] <= 100
题解
借助计数排序思想,使用 $cnt$ 数组统计每个高度出现的次数,然后对 $cnt$ 求前缀和,则某个高度 $height$ 应该出现的下标 $i$ 范围为 $cnt[height-1]\leq i<cnt[height]$。
代码
class Solution {
public:
int heightChecker(vector<int>& heights) {
vector<int> cnt(110, 0);
int ans = 0, n = heights.size();
for (int i = 0; i < n; ++i) {
++cnt[heights[i]];
}
for (int i = 1; i < 110; ++i) {
cnt[i] += cnt[i - 1];
}
for (int i = 0; i < n; ++i) {
if (cnt[heights[i] - 1] > i || i >= cnt[heights[i]]) {
++ans;
}
}
return ans;
}
};
复杂度分析
- 时间复杂度:$O(n+C)$,$C$ 为高度的最大值,这里直接 $C=110$。
- 空间复杂度:$O(C)$