Skip to content

Commit a13fb1f

Browse files
authored
feat: add swift implementation to lcof2 problem: No.010 (#2980)
1 parent f70118d commit a13fb1f

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lcof2/剑指 Offer II 010. 和为 k 的子数组/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,26 @@ function subarraySum(nums: number[], k: number): number {
143143
}
144144
```
145145

146+
#### Swift
147+
148+
```swift
149+
class Solution {
150+
func subarraySum(_ nums: [Int], _ k: Int) -> Int {
151+
var cnt: [Int: Int] = [0: 1]
152+
var ans = 0
153+
var s = 0
154+
155+
for x in nums {
156+
s += x
157+
ans += cnt[s - k, default: 0]
158+
cnt[s, default: 0] += 1
159+
}
160+
161+
return ans
162+
}
163+
}
164+
```
165+
146166
<!-- tabs:end -->
147167

148168
<!-- solution:end -->
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
func subarraySum(_ nums: [Int], _ k: Int) -> Int {
3+
var cnt: [Int: Int] = [0: 1]
4+
var ans = 0
5+
var s = 0
6+
7+
for x in nums {
8+
s += x
9+
ans += cnt[s - k, default: 0]
10+
cnt[s, default: 0] += 1
11+
}
12+
13+
return ans
14+
}
15+
}

0 commit comments

Comments
 (0)