[Swift]LeetCode346. 从数据流中移动平均值 $ Moving Average from Data Stream

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

For example,
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3


给定整数流和窗口大小,计算滑动窗口中所有整数的移动平均值。

例如,

MovingAverage m = new MovingAverage(3);

m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3


Solution:

 1 class MovingAverage {
 2     var q:[Int] = [Int]()
 3     var size:Int = 0
 4     var sum:Double = 0
 5     init(_ size:Int)
 6     {
 7         self.size = size
 8         sum = 0        
 9     }
10     
11     func next(_ val:Int) -> Double
12     {
13         if q.count >= size
14         {
15             let num:Double = Double(q.removeFirst())
16             sum -= num
17         }
18         q.append(val)
19         sum += Double(val)
20         return sum / Double(q.count)
21     }
22 }

点击:Playground测试

 1 var m:MovingAverage = MovingAverage(3)
 2 //m.next(1) = 1
 3 print(m.next(1))
 4 //Print 1.0
 5 
 6 //m.next(10) = (1 + 10) / 2
 7 print(m.next(10))
 8 //Print 5.5
 9 
10 //m.next(3) = (1 + 10 + 3) / 3
11 print(m.next(3))
12 //Print 4.666666666666667
13 
14 //m.next(5) = (10 + 3 + 5) / 3
15 print(m.next(5))
16 //Print 6.0

 

上一篇:11.闭包


下一篇:php – 如何使用avg功能?