题目要求: 给你一个整数数组 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
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold
解题思路: 采用滑窗法思想,建立一个长度为 k 的窗口,该窗口依次从数组左边中滑动到右边,每次窗口中的元素个数为k个。
算法步骤:
数组元素前 k 个元素相加和为 sum 窗口,判断是否大于 k*threshold ;从第 k + 1 个元素开始循环,sum 窗口加上下一个数组元素,减去 sum 窗口中的第一个元素,保证窗口中的元素为 k 个,判断新的 sum 是否大于 k*threshold 。代码:
class Solution { public static int numOfSubarrays(int[] arr, int k, int threshold) { int threshold_th = k*threshold; int count = 0; int sum = 0; for (int i = 0; i < k; i++) { sum += arr[i]; } if(sum >= threshold_th){ count++; } for(int i = k; i < arr.length; i++){ sum -= arr[i-k]; sum += arr[i]; if(sum >= threshold_th){ count++; } } return count; } }力扣测试结果 结果不一定最好,欢迎大家交流。