★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-vimoszqd-ha.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.git
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) / 3github
給定整數流和窗口大小,計算滑動窗口中全部整數的移動平均值。微信
例如,app
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) / 3spa
Solution:code
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測試htm
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