Table of Contents
中文版:
英文版:
My answer:
解题报告:
给你一个整数数组 arr 和两个整数 k 和 threshold 。
请你返回长度为 k 且平均值大于等于 threshold 的子数组数目。
示例 1:
输入:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
输出:3
解释:子数组 [2,5,5],[5,5,5] 和 [5,5,8] 的平均值分别为 4,5 和 6 。其他长度为 3 的子数组的平均值都小于 4 (threshold 的值)。
示例 2:
输入:arr = [1,1,1,1,1], k = 1, threshold = 0
输出:5
示例 3:
输入:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
输出:6
解释:前 6 个长度为 3 的子数组平均值都大于 5 。注意平均值不是整数。
示例 4:
输入:arr = [7,7,7,7,7,7,7], k = 7, threshold = 7
输出:1
示例 5:
输入:arr = [4,4,4,4], k = 4, threshold = 1
输出:1
提示:
1 <= arr.length <= 10^5
1 <= arr[i] <= 10^4
1 <= k <= arr.length
0 <= threshold <= 10^4
Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
Given an array of integers arr and two integers k and threshold.
Return the number of sub-arrays of size k and average greater than or equal to threshold.
Example 1:
Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output: 3
Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).
Example 2:
Input: arr = [1,1,1,1,1], k = 1, threshold = 0
Output: 5
Example 3:
Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
Output: 6
Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.
Example 4:
Input: arr = [7,7,7,7,7,7,7], k = 7, threshold = 7
Output: 1
Example 5:
Input: arr = [4,4,4,4], k = 4, threshold = 1
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 10^4
1 <= k <= arr.length
0 <= threshold <= 10^4
# 以下为未通过代码
class Solution:
def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
res = 0
l = len(arr)
for i in range(l-k+1):
j = 1
getsum = arr[i]
# print(getsum)
while j < k:
getsum += arr[i+j]
j += 1
avg = getsum / k
if avg >= threshold:
res += 1
return res
上述代码未通过的原因是超时。虽然题目中给的例子全部通过,但是仍报超时错误,再一次提醒我要看题目中给的限制。显然,本题中的限制1 <= arr.length <= 10^5 就在提醒不能用双重循环。
该解法思想:
遍历数组中的每个数,再看由每个数及后面的 k-1 个数是否满足题意。
既然双重循环会超时,则降低时间复杂度为 O(n) 即可。代码如下:
class Solution:
def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
res = 0
getsum = k * threshold
# 后面数的和大于getsum 即可,不用除以 k 求平均值与threshold比较
base = 0
# 先找出第一组 k 个数,判断是否满足条件
for i in range(k):
base += arr[i]
if base >= getsum:
res += 1
# 继续寻找数组,利用滑动窗口的思想,右边加一个数,左边减一个数,每次新数组都判断是否满足题意
for i in range(k,len(arr)):
base = base + arr[i] - arr[i-k]
if base >= getsum:
res += 1
return res
如上述代码中注释所写,本题算法为 “滑动窗口”。
注意能不开辟新空间就不开辟,若能用一个变量暂存结果就不要开数组。