leetcode1343. 大小为 K 且平均值大于等于阈值的子数组数目(队列)
生活随笔
收集整理的這篇文章主要介紹了
leetcode1343. 大小为 K 且平均值大于等于阈值的子数组数目(队列)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你一個整數數組 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 的值)。
代碼
class Solution {public int numOfSubarrays(int[] arr, int k, int threshold) {int sum=0,ans=0;Queue<Integer> queue=new LinkedList<>();for(int c:arr){if(queue.size()==k)//當前子數組滿足長度{if(sum>=k*threshold)//大于等于閾值ans++;sum-=queue.poll();}queue.offer(c);sum+=c;}if(sum>=k*threshold)ans++;return ans;} }總結
以上是生活随笔為你收集整理的leetcode1343. 大小为 K 且平均值大于等于阈值的子数组数目(队列)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode546. 移除盒子(dp
- 下一篇: leetcode面试题 16.04. 井