Skip to content

Commit 21520c1

Browse files
authored
feat: add swift implementation to lcof2 problem: No.011 (doocs#2981)
1 parent a13fb1f commit 21520c1

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

lcof2/剑指 Offer II 011. 0 和 1 个数相同的子数组/README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,29 @@ function findMaxLength(nums: number[]): number {
161161
}
162162
```
163163

164+
#### Swift
165+
166+
```swift
167+
class Solution {
168+
func findMaxLength(_ nums: [Int]) -> Int {
169+
var d: [Int: Int] = [0: -1]
170+
var ans = 0
171+
var s = 0
172+
173+
for i in 0..<nums.count {
174+
s += nums[i] == 0 ? -1 : 1
175+
if let prevIndex = d[s] {
176+
ans = max(ans, i - prevIndex)
177+
} else {
178+
d[s] = i
179+
}
180+
}
181+
182+
return ans
183+
}
184+
}
185+
```
186+
164187
<!-- tabs:end -->
165188

166189
<!-- solution:end -->
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
func findMaxLength(_ nums: [Int]) -> Int {
3+
var d: [Int: Int] = [0: -1]
4+
var ans = 0
5+
var s = 0
6+
7+
for i in 0..<nums.count {
8+
s += nums[i] == 0 ? -1 : 1
9+
if let prevIndex = d[s] {
10+
ans = max(ans, i - prevIndex)
11+
} else {
12+
d[s] = i
13+
}
14+
}
15+
16+
return ans
17+
}
18+
}

0 commit comments

Comments
 (0)