Skip to content

Commit f70118d

Browse files
authored
feat: add swift implementation to lcof2 problem: No.009 (#2979)
1 parent cf5e801 commit f70118d

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

lcof2/剑指 Offer II 009. 乘积小于 K 的子数组/README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,31 @@ function numSubarrayProductLessThanK(nums: number[], k: number): number {
149149
}
150150
```
151151

152+
#### Swift
153+
154+
```swift
155+
class Solution {
156+
func numSubarrayProductLessThanK(_ nums: [Int], _ k: Int) -> Int {
157+
if k <= 1 { return 0 }
158+
159+
var product: Int = 1
160+
var ans: Int = 0
161+
var left: Int = 0
162+
163+
for right in 0..<nums.count {
164+
product *= nums[right]
165+
while product >= k {
166+
product /= nums[left]
167+
left += 1
168+
}
169+
ans += right - left + 1
170+
}
171+
172+
return ans
173+
}
174+
}
175+
```
176+
152177
<!-- tabs:end -->
153178

154179
<!-- solution:end -->
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
func numSubarrayProductLessThanK(_ nums: [Int], _ k: Int) -> Int {
3+
if k <= 1 { return 0 }
4+
5+
var product: Int = 1
6+
var ans: Int = 0
7+
var left: Int = 0
8+
9+
for right in 0..<nums.count {
10+
product *= nums[right]
11+
while product >= k {
12+
product /= nums[left]
13+
left += 1
14+
}
15+
ans += right - left + 1
16+
}
17+
18+
return ans
19+
}
20+
}

0 commit comments

Comments
 (0)