加载中...
1343-大小为 K 且平均值大于等于阈值的子数组数目(Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold)
发表于:2021-12-03 | 分类: 中等
字数统计: 736 | 阅读时长: 3分钟 | 阅读量:

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

英文原文

Given an array of integers arr and two integers k and threshold.

Return the number of sub-arrays of size k and average greater than or equal to threshold.

 

Example 1:

Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output: 3
Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).

Example 2:

Input: arr = [1,1,1,1,1], k = 1, threshold = 0
Output: 5

Example 3:

Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
Output: 6
Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.

Example 4:

Input: arr = [7,7,7,7,7,7,7], k = 7, threshold = 7
Output: 1

Example 5:

Input: arr = [4,4,4,4], k = 4, threshold = 1
Output: 1

 

Constraints:

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

中文题目

给你一个整数数组 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

通过代码

高赞题解

思路:
step1 : 取出前k个数求和,然后减去k*threshold ,如果结果大于0,说明符合要求。
step2 : 指针后移一位,用后移一位的值减去移动之前的第一位的值,再加上上次减法的结果,如果大于0,说明符合要求

整体思路没有除法,只有增量的加减,而且加减数值非常小。请大家指点,评论出时间复杂度和空间复杂度。

public static int numOfSubarrays(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];
        }
        int adder = sum - sumTarget;
        if (adder >= 0) {
            result++;
        }
        int pos = k;
        for (int i = 0; i < arr.length-k; i++) {
            adder = adder+arr[pos]-arr[i];
            if (adder>=0){
                result++;
            }
            pos++;
        }
        return result;
    }

统计信息

通过次数 提交次数 AC比率
13164 24053 54.7%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
1342-将数字变成 0 的操作次数(Number of Steps to Reduce a Number to Zero)
下一篇:
1345-跳跃游戏 IV(Jump Game IV)
本文目录
本文目录