【leetcode】1343_ 大小为 K 且平均值大于等于阈值的子数组数目

链接

[https://leetcode-cn.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/]
难度中等


描述

给你一个整数数组 arr 和两个整数 kthreshold

请你返回长度为 k 且平均值大于等于 threshold 的子数组数目。


示例

示例 1:

输入: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 的值)。
示例 2:

输入:arr = [1,1,1,1,1], k = 1, threshold = 0
输出:5

AC代码

1.首先这道题的子数组指的是原数组中连续的k个数组成的数组,因此,原来的数组是不能够排序的。
2.如果子数组的和arr_sum大于等于k*threadhold则满足条件的子数组数量+1
3.利用滑窗法求解
 3.1 求前k个数的和arr_sum,看是否满足条件
 3.2 窗口向后滑动: arr_sum减上子数组中第一个元素的值,再加上数组后一位数的值。

class Solution 
{
public:
    int numOfSubarrays(vector<int>& arr, int k, int threshold)
    {
        int sum=0,result=0;
        int sumtarget=k*threshold;
        for(int i=0;i<k;i++)
        {
            sum+=arr[i];
        }  //前k个数之和
        int tmp=sum-sumtarget;
        if(tmp>=0)
            result++;  //sum大于等于目标值则记录
        int pos=k;
        for(int i=0;i<arr.size()-k;i++)
        {
            tmp=tmp+arr[pos]-arr[i];  //滑窗法,加上后面一个数减去第一个数
            if(tmp>=0)
                result++;
            pos++;
        }
        return result;  //返回记录值
    }
};
原文地址:https://www.cnblogs.com/tazimi/p/13302222.html