446. Rolling Average
A thermostat receives one temperature reading after another and smooths them by reporting the average of the most recent readings only. Old readings eventually stop counting, which keeps the displayed number responsive to changes.
Implement the class RollingAverage. Its constructor receives the window length size. Each call next(value) adds a new reading to the stream and returns the average of the last size readings as a floating-point number. If fewer than size readings have arrived so far, the average covers every reading received. Answers within 1e-5 of the exact value are accepted.
Example 1
- Input:
- operations = ["RollingAverage","next","next","next","next","next"]arguments = [[3],[4],[10],[-1],[7],[13]]
- Output:
- [null,4,7,4.333333333333333,5.333333333333333,6.333333333333333]
- Explanation:
Windows: [4] gives 4.0; [4, 10] gives 7.0; [4, 10, -1] gives 13/3 = 4.33333; then 4 leaves: [10, -1, 7] gives 16/3 = 5.33333; then 10 leaves: [-1, 7, 13] gives 19/3 = 6.33333.
Example 2
- Input:
- operations = ["RollingAverage","next","next","next","next"]arguments = [[2],[-6],[-6],[9],[2]]
- Output:
- [null,-6,-6,1.5,5.5]
- Explanation:
Windows: [-6] gives -6.0; [-6, -6] gives -6.0; [-6, 9] gives 1.5; [9, 2] gives 5.5.
Constraints
1 ≤ size ≤ 1000
-104 ≤ value ≤ 104
At most 104 calls to next.
How this problem is judged
- Answers
- Numbers are accepted within a tolerance of 1.0E-5: |answer - expected| <= 1.0E-5 x max(1, |expected|).
- Tolerance
0.00001- Input
- Each case is an operation log.
operationsnames the class first and then each method call;argumentsholds the arguments for each, in the same order. Your answer is one list with a result per operation -nullfor the constructor and for methods that return nothing.
Expected complexity
- Time
- O(1) per call
- Space
- O(size)