1343. 大小为 K 且平均值大于等于阈值的子数组数目(滑动窗口||前缀和)
题解:
滑动窗口和前缀和
1.
class Solution { public: int numOfSubarrays(vector<int>& arr, int k, int threshold) { //滑动窗口解法 int left=0; int right=k-1; int sum=0; for(int i=0;i<k;i++) sum+=arr[i]; int num=0; while(right+1<arr.size()) { if(sum/k>=threshold) num++; sum-=arr[left++]; sum+=arr[++right]; } if(sum/k>=threshold) num++; return num; } };
2.
class Solution { public: int numOfSubarrays(vector<int>& arr, int k, int threshold) { int sum[100005]={0}; int size=arr.size(); sum[0]=0; sum[1]=arr[0]; int ops=2; for(int i=1;i<size;i++) { sum[ops]=sum[ops-1]+arr[i];ops++; } int num=0; for(int i=k;i<=size;i++) { int pi=(sum[i]-sum[i-k])/k; //cout<<"pi="<<pi<<endl; if(pi>=threshold) num++; } return num; } };