LeetCode1343
/*题目描述:给定一个数组Array、子数组长度k、子数组平均值阀值threshold
* 求出 Array的长度小于k平均值大于等于threshold的子数组的数量。
*解题思路:维持指针tail指向子数组的尾部、指针head指向子数组头部,声明sum
* 记录当前子数组的和,每次将head、tail后移一位,sum=sum-tail+newHead
* 若sum/k大于等于threshold,result+1;
* */
public class Question1343 {
public static void main(String[] args) {
int[] arr = {11,13,17,23,29,31,7,5,2,3};
int k = 3;
int threshold = 5;
Question1343_Solution qs = new Question1343_Solution();
System.out.println(qs.numOfSubarrays(arr, k, threshold));
}
}
class Question1343_Solution {
public int numOfSubarrays(int[] arr, int k, int threshold) {
//声明子数组尾指针、头指针、和
int tail = 0;
int head = k-1;
int sum = 0;
//声明目标子数组的数量
int result = 0;
//遍历第一个子数组
for(int i = 0;i < k; i++) {
sum = sum+arr[i];
}
//遍历arr
while(head<arr.length) {
if((sum/k)>=threshold) {
result++;
}
if(head+1<arr.length) sum = sum-arr[tail]+arr[head+1];
tail+=1;
head+=1;
}
return result;
}
}