[Swift]LeetCode346. 从数据流中移动平均值 $ Moving Average from Data Stream
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10740116.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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