struct MovingAverage {
size: usize,
sum: i32,
q: std::collections::VecDeque<i32>,
}
/\*\*
\* `&self` means the method takes an immutable reference.
\* If you need a mutable reference, change it to `&mut self` instead.
\*/
impl MovingAverage {
/\*\* Initialize your data structure here. \*/
fn new(size: i32) -> Self {
MovingAverage{
size: size as usize,
sum: 0,
q: std::collections::VecDeque::new()
}
}
fn next(&mut self, val: i32) -> f64 {
if self.q.len() == self.size {
self.sum -= self.q.pop\_front().unwrap();
}
self.q.push\_back(val);
self.sum += val;
self.sum as f64 / self.q.len() as f64
}
}
/\*\*
\* Your MovingAverage object will be instantiated and called as such:
\* let obj = MovingAverage::new(size);
\* let ret\_1: f64 = obj.next(val);
\*/
go
type MovingAverage struct {
size int
sum int
q []int
}
/\*\* Initialize your data structure here. \*/
func Constructor(size int) MovingAverage {
return MovingAverage{size: size}
}
func (this \*MovingAverage) Next(val int) float64 {
if len(this.q) == this.size {
this.sum -= this.q[0]
this.q = this.q[1:]
}
this.sum += val
this.q = append(this.q, val)
return float64(this.sum) / float64(len(this.q))
}
/\*\*
\* Your MovingAverage object will be instantiated and called as such:
\* obj := Constructor(size);
\* param\_1 := obj.Next(val);
\*/
c++
class MovingAverage {
private:
int size;
int sum;
queue<int> q;
public:
/\*\* Initialize your data structure here. \*/
MovingAverage(int size) {
this->sum = 0;
this->size = size;
}
double next(int val) {
if (this->q.size() == this->size) {
this->sum -= this->q.front();
this->q.pop();
}
this->sum += val;
this->q.emplace(val);
return this->sum \* 1.0 / this->q.size();
}
};
/\*\*
\* Your MovingAverage object will be instantiated and called as such:
\* MovingAverage\* obj = new MovingAverage(size);
\* double param\_1 = obj->next(val);
\*/
java
class MovingAverage {
private final int size;
private int sum;
private final Queue<Integer> q = new LinkedList<>();
/\*\* Initialize your data structure here. \*/
public MovingAverage(int size) {
this.size = size;
}
public double next(int val) {
if (q.size() == size) {
sum -= q.poll();
}
sum += val;
q.offer(val);
return sum \* 1.0 / q.size();
}
}
/\*\*
\* Your MovingAverage object will be instantiated and called as such:
\* MovingAverage obj = new MovingAverage(size);
\* double param\_1 = obj.next(val);
\*/