/
MovingAverageFromDataStream.swift
64 lines (50 loc) · 1.37 KB
/
MovingAverageFromDataStream.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// MovingAverageFromDataStream.swift
// LeetCode.swift
//
// Created by 叶帆 on 2020/3/3.
// Copyright © 2020 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
/**
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
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
*/
import Foundation
class MovingAverage {
var data: [Int]
var size: Int
var sum: Int
/** Initialize your data structure here. */
init(_ size: Int) {
data = []
self.size = size
sum = 0
}
func next(_ val: Int) -> Double {
if data.count == size {
sum -= data[0]
data.remove(at: 0)
}
sum += val
data.append(val)
return (Double)(sum)/(Double)(data.count)
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* let obj = MovingAverage(size)
* let ret_1: Double = obj.next(val)
*/