LeetCode 346. 数据流中的移动平均值(队列)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 346. 数据流中的移动平均值(队列)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
給定一個整數數據流和一個窗口大小,根據該滑動窗口的大小,計算其所有整數的移動平均值。
示例: MovingAverage m = new MovingAverage(3); m.next(1) = 1 m.next(10) = (1 + 10) / 2 m.next(3) = (1 + 10 + 3) / 3 m.next(5) = (10 + 3 + 5) / 3來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/moving-average-from-data-stream
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
class MovingAverage {queue<int> q;int sum = 0;int cap; public:/** Initialize your data structure here. */MovingAverage(int size) {cap = size;}double next(int val) {sum += val;q.push(val);if(q.size() > cap){sum -= q.front();q.pop();}return sum/double(q.size());} };48 ms 13.5 MB
長按或掃碼關注我的公眾號,一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 346. 数据流中的移动平均值(队列)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 683. K 个空花盆
- 下一篇: LeetCode 815. 公交路线(最