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/

相关推荐
ん贤3 小时前
Go channel 深入解析
开发语言·后端·golang
夜天炫安全4 小时前
数据结构中所需的C语言基础
c语言·数据结构·算法
2301_789015624 小时前
DS进阶:AVL树
开发语言·数据结构·c++·算法
changhong19865 小时前
如何在 Spring Boot 中配置数据库?
数据库·spring boot·后端
Filotimo_6 小时前
5.3 Internet基础知识
开发语言·php
识君啊6 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
qyzm8 小时前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
月月玩代码8 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
逆境不可逃8 小时前
LeetCode 热题 100 之 64. 最小路径和 5. 最长回文子串 1143. 最长公共子序列 72. 编辑距离
算法·leetcode·动态规划
leluckys8 小时前
swift- Swift中常见的面试题
开发语言·汇编·swift