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 = [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
找到指定k个数,平均值大于threshold,返回符合条件的子数组个数。
answer one
Analysis:
Time & space: O(n), where n = a.length.
Prefix Sum:
public int numOfSubarrays(int[] a, int k, int threshold) {
int n = a.length, count = 0;
int[] prefixSum = new int[n + 1];
for (int i = 0; i < n; ++i)
prefixSum[i + 1] = prefixSum[i] + a[i];
for (int i = 0; i + k <= n; ++i)
if (prefixSum[i + k] - prefixSum[i] >= k * threshold)
++count;
return count;
}
造一个n+1长的数组,存前i个value的和。
然后遍历,用i+k的value-i的value就是k个value的和。然后与平均值*k比较。
聪明。
ANSWER TWO
Sliding Window:
Analysis:
Time: O(n), space: O(1), where n = a.length.
public int numOfSubarrays(int[] a, int k, int threshold) {
int count = 0;
for (int lo = -1, hi = 0, win = 0; hi < a.length; ++hi) {
win += a[hi];
if (hi - lo == k) {
if (win >= k * threshold)
++count;
win -= a[++lo];
}
}
return count;
}
answer three
class Solution {
public int numOfSubarrays(int[] arr, int k, int threshold) {
int n = arr.length, ans = 0, s = 0;
for(int i = 0; i < k - 1; i++) s += arr[i];
for(int i = k - 1; i < n; i++) {
s += arr[i];
if(s / k >= threshold) ans++;
s -= arr[i - k + 1];
}
return ans;
}
answer four
public int numOfSubarrays(int[] arr, int k, int threshold) {
int t = k * threshold, s = 0, cnt = 0;
for (int i = 0; i < arr.length; i++) {
s += arr[i];
if (i < k -1) continue;
if (i > k - 1) s -= arr[i - k];
if (s >= t) cnt++;
}
return cnt;
}