1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold - Medium

前往題目

想法

  • Sliding window

思路

簡單的那種固定window size

  1. 每次循環都更新總和
  2. 檢查平均,如果滿足threshold加入結果
  3. 循環結束前都移動左指針並且從sum減去相對應的數字

Code

class Solution {
    public int numOfSubarrays(int[] arr, int k, int threshold) {
        int l = 0;
        int res = 0;
        int sum = 0;

        for (int r = 0; r < arr.length; ++r) {
            // Skip window < k
            if (r - l + 1 != k) {
                sum += arr[r];
                continue;
            }

            sum += arr[r]; // Window is of size k

            int curAvg = sum / k; // Current average of window size k

            // Satisfy the threshold
            if (curAvg >= threshold) {
                ++res;
            }

            // Move left pointer to maintain window size k
            sum -= arr[l];
            ++l;
        }

        return res;
    }
}

1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold - Medium
https://f88083.github.io/2024/07/30/1343-Number-of-Sub-arrays-of-Size-K-and-Average-Greater-than-or-Equal-to-Threshold/
作者
Simon Lai
發布於
2024年7月30日
許可協議