Skip to content

Commit cf5e801

Browse files
authored
feat: add swift implementation to lcof2 problem: No.008 (#2978)
1 parent 42486a5 commit cf5e801

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

lcof2/剑指 Offer II 008. 和大于等于 target 的最短子数组/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,30 @@ function minSubArrayLen(target: number, nums: number[]): number {
176176
}
177177
```
178178

179+
#### Swift
180+
181+
```swift
182+
class Solution {
183+
func minSubArrayLen(_ target: Int, _ nums: [Int]) -> Int {
184+
let inf = Int.max
185+
var ans = inf
186+
var sum = 0
187+
var i = 0
188+
189+
for j in 0..<nums.count {
190+
sum += nums[j]
191+
while sum >= target {
192+
ans = min(ans, j - i + 1)
193+
sum -= nums[i]
194+
i += 1
195+
}
196+
}
197+
198+
return ans == inf ? 0 : ans
199+
}
200+
}
201+
```
202+
179203
<!-- tabs:end -->
180204

181205
<!-- solution:end -->
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
func minSubArrayLen(_ target: Int, _ nums: [Int]) -> Int {
3+
let inf = Int.max
4+
var ans = inf
5+
var sum = 0
6+
var i = 0
7+
8+
for j in 0..<nums.count {
9+
sum += nums[j]
10+
while sum >= target {
11+
ans = min(ans, j - i + 1)
12+
sum -= nums[i]
13+
i += 1
14+
}
15+
}
16+
17+
return ans == inf ? 0 : ans
18+
}
19+
}

0 commit comments

Comments
 (0)