Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 00b7e53

Browse files
feat: add swift implementation to lcof2 problem: No.041 (doocs#3051)
1 parent 282659b commit 00b7e53

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

‎lcof2/剑指 Offer II 041. 滑动窗口的平均值/README.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,36 @@ func (this *MovingAverage) Next(val int) float64 {
172172
*/
173173
```
174174

175+
#### Swift
176+
177+
```swift
178+
class MovingAverage {
179+
private var arr: [Int]
180+
private var s: Int
181+
private var cnt: Int
182+
183+
init(_ size: Int) {
184+
arr = [Int](repeating: 0, count: size)
185+
s = 0
186+
cnt = 0
187+
}
188+
189+
func next(_ val: Int) -> Double {
190+
let idx = cnt % arr.count
191+
s += val - arr[idx]
192+
arr[idx] = val
193+
cnt += 1
194+
return Double(s) / Double(min(cnt, arr.count))
195+
}
196+
}
197+
198+
/**
199+
* Your MovingAverage object will be instantiated and called as such:
200+
* let obj = MovingAverage(size)
201+
* let param_1 = obj.next(val)
202+
*/
203+
```
204+
175205
<!-- tabs:end -->
176206

177207
<!-- solution:end -->
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class MovingAverage {
2+
private var arr: [Int]
3+
private var s: Int
4+
private var cnt: Int
5+
6+
init(_ size: Int) {
7+
arr = [Int](repeating: 0, count: size)
8+
s = 0
9+
cnt = 0
10+
}
11+
12+
func next(_ val: Int) -> Double {
13+
let idx = cnt % arr.count
14+
s += val - arr[idx]
15+
arr[idx] = val
16+
cnt += 1
17+
return Double(s) / Double(min(cnt, arr.count))
18+
}
19+
}
20+
21+
/**
22+
* Your MovingAverage object will be instantiated and called as such:
23+
* let obj = MovingAverage(size)
24+
* let param_1 = obj.next(val)
25+
*/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /