Live2D

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

题目

给你一个整数数组 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] 的平均值分别为 4,5 和 6 。其他长度为 3 的子数组的平均值都小于 4 (threshold 的值)。

链接:https://leetcode-cn.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold

分析

数组 划窗

代码

C++ 208ms 52.3 MB

class Solution {
public:
    int numOfSubarrays(vector<int>& arr, int k, int threshold) {
        int ans=0,sum=0,targe=threshold*k;

        for(int i=0;i<arr.size();i++){
            sum+=arr[i];
            if(i<k-1) continue;
            else if(i>k-1)   sum-=arr[i-k];
            if(sum>=targe) ans++;
        }
        return ans;
    }
};

python 132 23.3MB

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

posted @ 2020-08-11 02:15  Duiliur  阅读(110)  评论(0编辑  收藏  举报