LeetCode 1051. 高度检查器
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
学校打算为全体学生拍一张年度纪念照。根据要求学生需要按照 非递减 的高度顺序排成一行。
排序后的高度情况用整数数组 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 处的学生高度不匹配。
1 <= heights.length <= 100
1 <= heights[i] <= 100
对数组排序然后对比排序前后数组有几个对应位置的元素不同
class Solution {
public:
int heightChecker(vector<int>& heights) {
vector<int> heightsBak = heights;
sort(heights.begin(), heights.end());
int ans = 0;
for (int i = 0; i < heights.size(); ++i) {
if (heightsBak[i] != heights[i]) {
++ans;
}
}
return ans;
}
};
如果输入数组长度为n此算法时间复杂度为Onlgn空间复杂度为O1。
题目中规定了1 <= heights[i] <= 100因此可用计数排序将时间复杂度降为On
class Solution {
public:
int heightChecker(vector<int>& heights) {
vector<int> countArr(100);
for (int i : heights) {
++countArr[i - 1];
}
int index = 0;
int ans = 0;
for (int i = 0; i < 100; ++i) {
if (!countArr[i]) {
continue;
}
while (countArr[i]) {
if (heights[index] != i + 1) {
++ans;
}
++index;
--countArr[i];
}
}
return ans;
}
};
如果高度范围为m输入数组长度为n此算法时间复杂度为On空间复杂度为Om。