class MovingAverage {
/** Initialize your data structure here. */
private var stack = [Int]()
private let size: Int
private var sum = 0
init(_ size: Int) {
self.size = size
}
func next(_ val: Int) -> Double {
if stack.count < self.size {
stack.append(val)
sum += val
return Double(sum) / Double(stack.count)
} else {
sum -= stack.removeFirst()
stack.append(val)
sum += val
return Double(sum) / Double(self.size)
}
}
}
More than 5 years have passed since last update.
Leetcode #346: Moving Average From Data Stream
Last updated at Posted at 2019-08-01
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme