文章目录
- 题目描述
- 题解思路
- 题解代码
- 题解链接
题目描述
题解思路
半径为 k 的子数组平均值 等价于 子数组长度为2 * k + 1的总和 除于 2 * k + 1
我们遍历长度为2 * k + 1的窗口,我们只需要记录窗口内的平均值即可
题解代码
rust">impl Solution {pub fn get_averages(nums: Vec<i32>, k: i32) -> Vec<i32> {let n = ((k << 1) + 1) as usize;let mut ans = vec![-1; nums.len()];if n > ans.len() {return ans;}let mut sum = 0;for i in 0..n {sum += nums[i] as usize;}for i in k as usize..(nums.len() - k as usize) {ans[i] = (sum / n) as i32;if i != nums.len() - k as usize - 1 {sum += (nums[i + k as usize + 1] - nums[i - k as usize]) as usize;}}ans}
}
题解链接
https://leetcode.cn/problems/k-radius-subarray-averages/description/