Leetcode 1343.大小为 K 且平均值大于等于阈值的子数组数目

Leetcode 1343.大小为 K 且平均值大于等于阈值的子数组数目

1 题目描述(Leetcode题目链接)

  给你一个整数数组 arr 和两个整数 k 和 threshold 。请你返回长度为 k 且平均值大于等于 threshold 的子数组数目。

输入:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
输出:3
解释:子数组 [2,5,5],[5,5,5][5,5,8] 的平均值分别为 456 。其他长度为 3 的子数组的平均值都小于 4 (threshold 的值)
输入:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
输出:6
解释:前 6 个长度为 3 的子数组平均值都大于 5 。注意平均值不是整数。

2 题解

  子数组要求连续,因此使用前缀和来做很方便。

class Solution:
    def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
        res = 0
        arr = [0] + arr
        for i in range(1, len(arr)):
            arr[i] += arr[i-1]
            if i >= k and arr[i] - arr[i-k] >= k*threshold:
                res += 1
        return res

你可能感兴趣的:(Leetcode)