文章目录
题目描述
题解思路
我们遍历长度为k的的窗口
因为数据范围比较小,所以我们可以通过计数排序找到窗口中第k小的数
- 如果小于0,则该窗口的美丽值为第k小的数
- 如果大于等于0,则该窗口的美丽值为0
题解代码
rust
impl Solution {
pub fn get_subarray_beauty(nums: Vec<i32>, k: i32, x: i32) -> Vec<i32> {
let mut cnt = [0; 101];
let get_beauty = |cnt: &mut [i32]| -> i32 {
let mut count = 0;
for i in 0..101 {
count += cnt[i];
if count >= x {
if i < 50 {
return i as i32 - 50;
}
return 0
}
}
0
};
for i in 0..k as usize {
cnt[(nums[i] + 50) as usize] += 1;
}
let mut ans = vec![0; nums.len() - k as usize + 1];
ans[0] = get_beauty(&mut cnt);
for i in k as usize..nums.len() {
cnt[(nums[i - k as usize] + 50) as usize] -= 1;
cnt[(nums[i] + 50) as usize] += 1;
ans[i - k as usize + 1] = get_beauty(&mut cnt);
}
ans
}
}