Rust 力扣 - 2653. 滑动子数组的美丽值
题目描述
题解思路
我们遍历长度为k的的窗口
因为数据范围比较小,所以我们可以通过计数排序找到窗口中第k小的数
- 如果小于0,则该窗口的美丽值为第k小的数
- 如果大于等于0,则该窗口的美丽值为0
题解代码
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
}
}
题目链接
https://leetcode.cn/problems/sliding-subarray-beauty/
原文地址:https://blog.csdn.net/qq_67733273/article/details/143449660
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!