求一个数列的某个移动窗口的平均值(窗口大小2*k+1,窗口和整除),若窗口长度不够,该位置输出-1,移动窗口基本应用
1 #2090
2 #Runtime: 1555 ms (Beats 43.86%)
3 #Memory: 33.2 MB (Beats 91.23%)
4
5 class Solution(object):
6 def getAverages(self, nums, k):
7 """
8 :type nums: List[int]
9 :type k: int
10 :rtype: List[int]
11 """
12 t = 0
13 if len(nums) < 2 * k + 1:
14 ans = [-1] * len(nums)
15 return ans
16 ans = [-1] * k
17 for i in range(0, len(nums)):
18 t += nums[i]
19 if i >= 2 * k + 1:
20 t -= nums[i - 2 * k - 1]
21 if i >= 2 * k:
22 ans.append(t // (2 * k + 1))
23 if len(nums) > 1:
24 ans.extend([-1] * k)
25 return ans