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

文章目录

题目描述

题解思路

长度为k且平均值大于等于阈值的子数组数目 等于 长度为k且总和大于等于k * 阈值的子数组数目

我们遍历长度为k的窗口,我们只需要记录窗口内的总和即可,遍历过程中记录总和大于等于k * 阈值的子数组数目

题解代码

rust 复制代码
impl Solution {
    pub fn num_of_subarrays(arr: Vec<i32>, k: i32, threshold: i32) -> i32 {    
        let threshold = k * threshold;

        let mut ans = 0;
        let mut sum = 0;

        for i in 0..k as usize {
            sum += arr[i];
        }

        if sum >= threshold {
            ans += 1;
        }

        for i in k as usize..arr.len() {
            sum += arr[i] - arr[i - k as usize];
            if sum >= threshold {
                ans += 1;
            }
        }

        ans
    }
}

题目链接

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

相关推荐
科雷软件测试1 小时前
Python中itertools.product:快速生成笛卡尔积
开发语言·python
OOJO2 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
IT_陈寒2 小时前
React Hooks闭包陷阱:你以为的state可能早就过期了
前端·人工智能·后端
小码哥_常2 小时前
细说API:颠覆认知!重新认识RESTful的真正精髓
后端
用户99045017780092 小时前
基于flowable实现在线表单+工作流
后端
苏三说技术2 小时前
Artha已接入MCP,线上问题能用AI排查了!
后端
用户962377954482 小时前
代码审计 | CC2 链 —— _tfactory 赋值问题 PriorityQueue 新入口
后端
别或许3 小时前
1、高数----函数极限与连续(知识总结)
算法
派大星~课堂4 小时前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
田梓燊4 小时前
code 560
数据结构·算法·哈希算法