【array-java】1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold

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;
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值