[算法练习]第三天:定长滑动窗口

643. 子数组最大平均数 I

切记,这里的三段式

右指针入队列-》判断-》左指针出队列以备下一次判断

因为这里只需要最后返回平均值,所以只需要最后进行强制类型转换为double即可,不需要提前把变量设置为double

cpp 复制代码
class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        int ans = INT_MIN;
        int temp = 0;
        for(int right = 0; right < nums.size(); right++){
            // 右指针
            temp += nums[right];
            //判断
            int left = right - k + 1;
            if(left < 0) continue;
            ans = max(ans,temp);
            //左指针出队列,以备下一次入队列
            temp -= nums[left];
        }
        return (double)ans/k;
    }
};

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

思路一点没变

cpp 复制代码
class Solution {
public:
    int numOfSubarrays(vector<int>& arr, int k, int threshold) {
        int ans = 0;
        int temp = 0;
        for(int right = 0;right < arr.size();right++){
            temp += arr[right];

            int left = right - k + 1;
            if(left < 0) continue;
            if(temp >= threshold*k) ans++;

            temp -= arr[left];
        }
        return ans;
    }
};

2090. 半径为 k 的子数组平均值

思路很像,几乎没什么区别,这里注意示例元素和可能会超过int,要用long long;数组初始化使用-1会方便很多;

cpp 复制代码
class Solution {
public:
    vector<int> getAverages(vector<int>& nums, int k) {
        vector<int>ans(nums.size(),-1);
        long long temp = 0;
        for(int right = 0;right < nums.size();right++){
            temp += nums[right];
            
            int left = right - 2*k ;
            if(left < 0) continue;
            //判断
            ans[(left+right)/2] = temp/(2*k+1);

            temp -= nums[left];
        }
        return ans;
    }
};
相关推荐
倒头就睡的小比特1 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼1 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
m0_547486661 天前
《数据结构教程》全套 PPT课件2026
数据结构
旖旎夜光1 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark1 天前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her11 天前
并查集-听课笔记
笔记·算法·并查集
码流子1 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
another heaven1 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
wzdark1 天前
从算法设计模式看编程思维的抽象能力4
算法