1343. 大小为 K 且平均值大于等于阈值的子数组数目
给你一个整数数组 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
解题注意事项
一定要注意,子数组的概念,子数组是连续的,非子片段(或子集)的概念哈。
改进过程
- 第一次:开始直接K个元素求和,导致运行时间过长,提交失败;
- 第二次:先求和指定连续长度子数组的和,需要额外申请一组 arrSize+1的空间;
- 第三次:最终调整为浮窗滑动解决,代码过程如下。
解法
int numOfSubarrays(int* arr, int arrSize, int k, int threshold){
if (arr == NULL || arrSize <= 0 || k <= 0 || k > arrSize) {
return 0;
}
int thresholdSumMin = threshold * k;
int count = 0;
int sum = 0;
//创建浮窗
for (int i = 0; i < k; i++) {
sum += arr[i];
}
//判断初创浮窗满足条件否
if (sum >= thresholdSumMin) {
count = 1;
}
//开始浮窗滑动求和
for (int i = k; i < arrSize; i++) {
sum += arr[i] - arr[i-k];
//避免使用除法,提升运算效率
if (sum >= thresholdSumMin) {
count++;
}
}
return count;
}
全部代码:
#include <stdio.h>
int numOfSubarrays(int* arr, int arrSize, int k, int threshold){
if (arr == NULL || arrSize <= 0 || k <= 0 || k > arrSize) {
return 0;
}
int thresholdSumMin = threshold * k;
int count = 0;
int sum = 0;
//创建浮窗
for (int i = 0; i < k; i++) {
sum += arr[i];
}
//判断初创浮窗满足条件否
if (sum >= thresholdSumMin) {
count = 1;
}
//开始浮窗滑动求和
for (int i = k; i < arrSize; i++) {
sum += arr[i] - arr[i-k];
//避免使用除法,提升运算效率
if (sum >= thresholdSumMin) {
count++;
}
}
return count;
}
void children_array(int a[], int length) {
int max_mask = 1 << length;
for (int mask = 0; mask < max_mask; mask++) {
int empty_flag = 1;
//find length = n array
int sum = 0;
for (int mask_i = 0; mask_i < length; mask_i++) {
sum += (mask>>mask_i) & 1;
}
if (sum != 3) {
continue;
}
for (int i = 0; i < length; i++) {
// printf("mask=%d 1<<i=%d a[i]=%d\n", mask, 1 << i, a[i]);
if ( 1 << i & mask ) {
empty_flag = 0;
printf("%d,", a[i]);
}
}
if (empty_flag) {
printf("[]");
}
printf("\n##########################\n");
}
}
int main () {
int count = 0;
int a[8] = {2,2,2,2,5,5,5,8};
int b[5] = {1,1,1,1,1};
int c[10] = {11,13,17,23,29,31,7,5,2,3};
int d[7] = {7,7,7,7,7,7,7};
int e[4] = {4,4,4,4};
for (int i = 0 ; i < 5; i++) {
printf("%d ", a[i]);
}
printf("\n");
count = numOfSubarrays(a, 8, 3, 4);
printf("count=%d\n", count);
count = numOfSubarrays(b, 5, 1, 0);
printf("count=%d\n", count);
count = numOfSubarrays(c, 10, 3, 5);
printf("count=%d\n", count);
count = numOfSubarrays(d, 7, 7, 1);
printf("count=%d\n", count);
count = numOfSubarrays(e, 4, 4, 1);
printf("count=%d\n", count);
return 0;
}