本文已参与「新人创作礼」活动, 一起开启掘金创作之路。
1051. 高度检查器
来源:力扣(LeetCode)
学校打算为全体学生拍一张年度纪念照。根据要求,学生需要按照 非递减 的高度顺序排成一行。
排序后的高度情况用整数数组 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 处的学生高度不匹配。
示例 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 <= 100
1 <= heights[i] <= 100
解法
思路,题目意思很简单,就是应用排序的方法,然后比较原始数组与排序后的数组二者相同下标下不同元素的个数
- 快排:时间复杂度;
- 计数排序: 其实并不关心排序后得到的结果,我们想知道的只是在该位置上,与最小的值是否一致。题目中已经明确了值的范围 1 <= heights[i] <= 100,这是一个在固定范围内的输入,比如输入: [1,1,4,2,1,3],输入中有 3 个 1,1 个 2,1 个 3 和 1 个 4,3 个 1 肯定会在前面,依次类推。所以,我们需要的仅仅只是计数而已
代码实现
快排
python实现
class Solution:
def heightChecker(self, heights: List[int]) -> int:
n = len(heights)
heightss = sorted(heights)
res = 0
for i in range(n):
if heights[i] != heightss[i]:
res += 1
return res
class Solution:
def heightChecker(self, heights: List[int]) -> int:
expected = sorted(heights)
return sum(1 for x, y in zip(heights, expected) if x != y)
c++实现
class Solution {
public:
int heightChecker(vector<int>& heights) {
int n = heights.size();
vector<int> expected(heights);
sort(expected.begin(), expected.end());
int res = 0;
for (int i=0; i<n; i++) {
if (heights[i] != expected[i])
res++;
}
return res;
}
};
复杂度分析
- 时间复杂度:
- 空间复杂度:
计数排序
python实现
class Solution:
def heightChecker(self, heights: List[int]) -> int:
# 计数排序
m = max(heights)
c = [0] * (m+1)
for height in heights:
c[height] += 1
ans = 0
idx = 0
for i in range(1, m+1):
for j in range(c[i]):
if heights[idx] != i:
ans += 1
idx += 1
return ans
c++实现
class Solution {
public:
int heightChecker(vector<int>& heights) {
int m = *max_element(heights.begin(), heights.end());
vector<int> counts(m+1);
for (int height: heights) {
counts[height]++;
}
int ans = 0, idx = 0;
for (int i=1; i<m+1; i++) {
for (int j=0; j<counts[i]; j++) {
if (heights[idx] != i)
ans++;
idx++;
}
}
return ans;
}
};
复杂度分析
- 时间复杂度:
- 空间复杂度: