在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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 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
|
请发表评论