Medium
LABK Radius Subarray Averages
For each index, return the integer average of the subarray centered there with radius k, or -1 when the full window does not fit.
EXAMPLES
Example 1
Input
{
"nums": [
7,
4,
3,
9,
1,
8,
5,
2,
6
],
"k": 3
}
Output
[
-1,
-1,
-1,
5,
4,
4,
-1,
-1,
-1
]FUNCTION SHAPE
nums: intArrayk: int→intArraySOLUTION NOTE
Note: k in this case refers to one side of the array, so the window is of size 2k+1. We want to update index i-k in res, because that's the midpoint index of the window.
Reveal reference solution +
pythonREFERENCE
def getAverages(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
res = [-1] * n
sum_ = 0
for i in range(n):
sum_ += nums[i]
if i >= 2 * k:
res[i - k] = sum_ // (2 * k + 1)
sum_ -= nums[i - 2 * k]
return resTime
O(n)Space
O(n)