-
Notifications
You must be signed in to change notification settings - Fork 3
/
16-qIsx9U.rs
37 lines (33 loc) · 882 Bytes
/
16-qIsx9U.rs
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
// https://leetcode.cn/problems/qIsx9U/
struct MovingAverage {
size: i32,
nums: Vec<i32>,
sum: i64,
}
/**
* `&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 {
Self {
size,
nums: Vec::new(),
sum: 0,
}
}
fn next(&mut self, val: i32) -> f64 {
self.nums.push(val);
self.sum += val as i64;
if self.nums.len() > self.size as usize {
self.sum -= self.nums.remove(0) as i64;
}
(self.sum as f64) / (self.nums.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);
*/