Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
给一个数组arr, 求里面大小为k的sub array的平均值大于等于threshold的个数. running sum就可以.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Solution { public int numOfSubarrays(int[] arr, int k, int threshold) { int count = 0; int s = 0; for(int i = 0; i <= arr.length; i++) { if(i < k){ s += arr[i]; continue; } if((double) s / k >= threshold) count++; if(i == arr.length) break; s -= arr[i - k]; s += arr[i]; } return count; } } |