算法LeetCode自主学习------大小为 K 且平均值大于等于阈值的子数组数目

此题看了答案,算法最近刚开始练习,中等难度的对我来说还是有点难度,而且白天要上班,晚上偶尔练习,时间不太够,每次思考一个小时左右做不出来只能看答案,希望以后做多了能好点吧,继续加油

package test.java.first;

import org.junit.Test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 给你一个整数数组 arr 和两个整数 k 和 threshold 。

 请你返回长度为 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
 示例 3:

 输入:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
 输出:6
 解释:前 6 个长度为 3 的子数组平均值都大于 5 。注意平均值不是整数。
 示例 4:

 输入:arr = [7,7,7,7,7,7,7], k = 7, threshold = 7
 输出:1
 示例 5:

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

 提示:

 1 <= arr.length <= 10^5
 1 <= arr[i] <= 10^4
 1 <= k <= arr.length
 0 <= threshold <= 10^4

 来源:力扣(LeetCode)
 链接:https://leetcode-cn.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold
 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 *
 */
public class Sixteen {
    @Test
    public void test(){
    }
    public int numOfSubarrays(int[] arr, int k, int threshold) {
        int sum=0;
        int count=0;
        int total=k*threshold;
        for (int i = 0; i < k; i++) {
            sum=sum+arr[i];
        }
        int result=sum-total;

        if (result>=0){
            count++;
        }
        int pos=k;
        for (int i = 0; i < arr.length-k; i++) {
            result=result+arr[pos]-arr[i];
            if (result>=0){
                count++;
            }
            pos++;
        }
        return count;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值