-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0346_moving_average_from_data_stream.rs
More file actions
53 lines (46 loc) · 1.22 KB
/
s0346_moving_average_from_data_stream.rs
File metadata and controls
53 lines (46 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#![allow(unused)]
use std::collections::VecDeque;
struct MovingAverage {
window: VecDeque<i32>,
len: usize,
}
/**
* `&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 {
if size < 1 {
return Self {
window: VecDeque::new(),
len: 0,
};
}
Self {
window: VecDeque::with_capacity(size as usize),
len: size as usize,
}
}
fn next(&mut self, val: i32) -> f64 {
if self.window.len() == self.len {
self.window.pop_front();
self.window.push_back(val);
return self.window.iter().sum::<i32>() as f64 / self.window.len() as f64;
}
self.window.push_back(val);
return self.window.iter().sum::<i32>() as f64 / self.window.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);
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_346() {
}
}