问题:
给定一个数组,求其中连续K个元素组成的子数组中,平均值>=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
解法:
⚠️ 注意:
关于 Sub-arrays 的定义:
Subarrays are arrays within another array.Subarrays contains contiguous elements whereas subsequences are not.
An Example would make it clear
Consider an array {1,2,3,4}
List of all its subarrays are {},{1},{2},{3},{4},{1,2},{2,3},{3,4},{1,2,3,4}
List of all its subsequences are {},{1},{2},{3},{4},{1,2},{1,3},{1,4},{2,3},{2,4},{3,4},{1,2,3},{1,2,4},{1,3,4},{2,3,4},{1,2,3,4}
解法一:
Sliding windows 滑动窗口
遍历累加元素,到第k个元素后,没向后移动一个元素,同时减去前面的一个元素。
按照窗口大小为k,向右移动。
同时判断,当前窗口的元素和sum是否>=threshold*k
满足:res++
代码参考:
1 class Solution { 2 public: 3 int numOfSubarrays(vector<int>& arr, int k, int threshold) { 4 int sum=0, thresum=threshold*k; 5 int res=0; 6 for(int i=0; i<arr.size(); i++){ 7 sum+=arr[i]; 8 if(i>=k) sum-=arr[i-k]; 9 if(i>=k-1 && sum>=thresum) res++; 10 } 11 return res; 12 } 13 };
解法二:
Prefix Sum 前缀和
计算到当前元素为止,所有元素之和,记录到presum列表中。
初始化presum[0]=0
到第k个元素开始,判断presum[i+1]-presum[i-k+1]=当前元素开始向前推k个元素和 是否>=threshold*k
满足:res++
代码参考:
1 class Solution { 2 public: 3 int numOfSubarrays(vector<int>& arr, int k, int threshold) { 4 vector<int> presum(arr.size()+1, 0); 5 int thresum=threshold*k; 6 int res=0; 7 for(int i=0; i<arr.size(); i++){ 8 presum[i+1]=presum[i]+arr[i]; 9 if(i>=k-1 && presum[i+1]-presum[i-k+1]>=thresum) res++; 10 } 11 return res; 12 } 13 };