学校打算为全体学生拍一张年度纪念照。根据要求,学生需要按照 非递减 的高度顺序排成一行。
排序后的高度情况用整数数组 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 处的学生高度不匹配。
输入:
heights = [5,1,2,3,4]
输出:
5
解释:
高度:[5,1,2,3,4]
预期:[1,2,3,4,5]
所有下标的对应学生高度都不匹配。
输入:
heights = [1,2,3,4,5]
输出:
0
解释:
高度:[1,2,3,4,5]
预期:[1,2,3,4,5]
所有下标的对应学生高度都匹配。
1 <= heights.length <= 1001 <= heights[i] <= 100impl Solution {
pub fn height_checker(heights: Vec<i32>) -> i32 {
let mut cpy = heights.clone();
cpy.sort();
(0..heights.len()).filter(|&i| {
heights[i] != cpy[i]
}).count() as i32
}
}
func heightChecker(heights []int) int {
cpy := append([]int{}, heights...)
sort.Ints(cpy)
ans := 0
for i, h := range heights {
if h != cpy[i] {
ans++
}
}
return ans
}
function heightChecker(heights: number[]): number {
const cpy = heights.slice().sort((a, b) => a - b);
return heights.filter((h, i) => h != cpy[i]).length;
};
class Solution:
def heightChecker(self, heights: List[int]) -> int:
cpy = sorted(heights)
ans = 0
for i, h in enumerate(heights):
if h != cpy[i]:
ans += 1
return ans
static inline cmp(const void *a, const void *b) {
return *(int *) a - *(int *) b;
}
int heightChecker(int* heights, int heightsSize){
int *cpy = (int *) malloc(sizeof(int) * heightsSize);
memcpy(cpy, heights, sizeof(int) * heightsSize);
qsort(cpy, heightsSize, sizeof(int), cmp);
int ans = 0;
for (int i = 0; i < heightsSize; ++i) {
if (heights[i] != cpy[i]) {
++ans;
}
}
return ans;
}
class Solution {
public:
int heightChecker(vector<int>& heights) {
vector<int> cpy(heights);
sort(cpy.begin(), cpy.end());
int ans = 0;
for (int i = 0; i < heights.size(); ++i) {
if (heights[i] != cpy[i]) {
++ans;
}
}
return ans;
}
};
class Solution {
public int heightChecker(int[] heights) {
int[] cpy = Arrays.copyOf(heights, heights.length);
Arrays.sort(cpy);
int ans = 0;
for (int i = 0; i < heights.length; ++i) {
if (heights[i] != cpy[i]) {
++ans;
}
}
return ans;
}
}
class Solution {
public int heightChecker(int[] heights) {
// 对高度计数
int[] cnt = new int[101];
for (int h : heights) {
++cnt[h];
}
int idx = 0, ans = 0;
for (int h = 1; h <= 100; ++h) {// 按顺序遍历高度
for (int i = 0; i < cnt[h]; ++i) {// 高度的数量
if (heights[idx] != h) {
++ans;
}
// 移动位置
++idx;
}
}
return ans;
}
}
非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~