|
43 | 43 |
|
44 | 44 | <!-- 这里可写通用的实现逻辑 -->
|
45 | 45 |
|
| 46 | +**方法一:滑动窗口** |
| 47 | + |
| 48 | +我们可以维护一个长度为 $k$ 的滑动窗口,窗口内的元素之和为 $s$,每次判断 $\frac{s}{k}$ 是否大于等于 $threshold$,如果大于等于,则满足条件的子数组个数加一。 |
| 49 | + |
| 50 | +最后返回满足条件的子数组个数即可。 |
| 51 | + |
| 52 | +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $arr$ 的长度。 |
| 53 | + |
46 | 54 | <!-- tabs:start -->
|
47 | 55 |
|
48 | 56 | ### **Python3**
|
49 | 57 |
|
50 | 58 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
51 | 59 |
|
52 | 60 | ```python
|
53 |
| - |
| 61 | +class Solution: |
| 62 | + def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int: |
| 63 | + s = sum(arr[:k]) |
| 64 | + ans = int(s / k >= threshold) |
| 65 | + for i in range(k, len(arr)): |
| 66 | + s += arr[i] |
| 67 | + s -= arr[i - k] |
| 68 | + ans += int(s / k >= threshold) |
| 69 | + return ans |
54 | 70 | ```
|
55 | 71 |
|
56 | 72 | ### **Java**
|
57 | 73 |
|
58 | 74 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
59 | 75 |
|
60 | 76 | ```java
|
| 77 | +class Solution { |
| 78 | + public int numOfSubarrays(int[] arr, int k, int threshold) { |
| 79 | + int s = 0; |
| 80 | + for (int i = 0; i < k; ++i) { |
| 81 | + s += arr[i]; |
| 82 | + } |
| 83 | + int ans = s / k >= threshold ? 1 : 0; |
| 84 | + for (int i = k; i < arr.length; ++i) { |
| 85 | + s += arr[i] - arr[i - k]; |
| 86 | + ans += s / k >= threshold ? 1 : 0; |
| 87 | + } |
| 88 | + return ans; |
| 89 | + } |
| 90 | +} |
| 91 | +``` |
| 92 | + |
| 93 | +### **C++** |
| 94 | + |
| 95 | +```cpp |
| 96 | +class Solution { |
| 97 | +public: |
| 98 | + int numOfSubarrays(vector<int>& arr, int k, int threshold) { |
| 99 | + int s = accumulate(arr.begin(), arr.begin() + k, 0); |
| 100 | + int ans = s >= k * threshold; |
| 101 | + for (int i = k; i < arr.size(); ++i) { |
| 102 | + s += arr[i] - arr[i - k]; |
| 103 | + ans += s >= k * threshold; |
| 104 | + } |
| 105 | + return ans; |
| 106 | + } |
| 107 | +}; |
| 108 | +``` |
61 | 109 |
|
| 110 | +### **Go** |
| 111 | +
|
| 112 | +```go |
| 113 | +func numOfSubarrays(arr []int, k int, threshold int) (ans int) { |
| 114 | + s := 0 |
| 115 | + for _, x := range arr[:k] { |
| 116 | + s += x |
| 117 | + } |
| 118 | + if s/k >= threshold { |
| 119 | + ans++ |
| 120 | + } |
| 121 | + for i := k; i < len(arr); i++ { |
| 122 | + s += arr[i] - arr[i-k] |
| 123 | + if s/k >= threshold { |
| 124 | + ans++ |
| 125 | + } |
| 126 | + } |
| 127 | + return |
| 128 | +} |
62 | 129 | ```
|
63 | 130 |
|
64 | 131 | ### **...**
|
|
0 commit comments