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.

给数组arr,问有多少个长度为k的连续子数组和的均值大于threshold

滑动窗口求和解决

class Solution(object):
    def numOfSubarrays(self, arr, k, threshold):
        """
        :type arr: List[int]
        :type k: int
        :type threshold: int
        :rtype: int
        """
        threshold = k * threshold
        sumk = sum(arr[:k])
        ans = 1 if sumk >= threshold else 0
        for i in range(k, len(arr), 1):
            sumk = sumk + arr[i] - arr[i - k]
            ans += 1 if sumk >= threshold else 0
        return ans

 

posted @ 2020-07-22 13:59  whatyouthink  阅读(85)  评论(0编辑  收藏  举报