[LeetCode] 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold 大小為 K 且平均值大于等于閾值的子數組數目
Given an array of integers arr and two integers k and threshold, return *the number of sub-arrays of size k and average greater than or equal to *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 = [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.
Constraints:
1 <= arr.length <= 10^51 <= arr[i] <= 10^41 <= k <= arr.length0 <= threshold <= 10^4
這道題給了一個正整數數組 arr,和兩個參數k,threshold。說是讓找出所有長度為k的子數組的個數,使得該子數組的平均值大于等于 threshold。子數組的平均值的計算方法即為子數組之和除以其長度,這里就是除以k。而求子數組之和的問題,博主下意識的就會想到建立累加和數組,這樣可以快速求出任意長度的子數組之和。這里也可以用這種方法,建立累加和數組 sums,然后就是遍歷所有的長度為k的子數組,然后通過 sums[i]-sums[i-k] 快速得到其數組之和。接下來就要進行比較了,這里博主沒有使用除法,因為除法沒有乘法高效,用k乘以 threshold 的結果進行比較也是一樣的,若滿足條件,則結果自增1即可,參見代碼如下:
解法一:
class Solution {
public:
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
int res = 0, n = arr.size(), target = k * threshold;
vector<int> sums(n + 1);
for (int i = 1; i <= n; ++i) {
sums[i] = sums[i - 1] + arr[i - 1];
}
for (int i = k; i <= n; ++i) {
int sum = sums[i] - sums[i - k];
if (sum >= target) ++res;
}
return res;
}
};
由于這道題只關心長度為k的子數組,那么建立整個累加和數組就略顯多余了,只要維護一個大小為k的窗口就能遍歷所有長度為k的子數組了。這就是滑動窗口 Sliding Window 的思路,遍歷數組,將當前數字加到 sum 中,若i大于等于k,說明此時窗口大小超過了k,需要把左邊界 arr[i-k] 減去,然后把 sum 跟 target 進行比較,注意這里的i必須要大于等于 k-1,因為要保證窗口的大小正好是k,參見代碼如下:
解法二:
class Solution {
public:
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
int res = 0, n = arr.size(), sum = 0, target = k * threshold;
for (int i = 0; i < n; ++i) {
sum += arr[i];
if (i >= k) sum -= arr[i - k];
if (i >= k - 1 && sum >= target) ++res;
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1343
類似題目:
K Radius Subarray Averages
Count Subarrays With Median K
參考資料:


浙公網安備 33010602011771號