LoginSignup
0
0

More than 3 years have passed since last update.

Leetcode #346: Moving Average From Data Stream

Last updated at Posted at 2019-08-01
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)
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0