Skip to content

Commit 675b557

Browse files
authored
feat: add swift implementation to lcof problem: No.66 (#2961)
1 parent 9a16d7b commit 675b557

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lcof/面试题66. 构建乘积数组/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,33 @@ public class Solution {
188188
}
189189
```
190190

191+
#### Swift
192+
193+
```swift
194+
class Solution {
195+
func constructArr(_ a: [Int]) -> [Int] {
196+
let n = a.count
197+
guard n > 0 else { return [] }
198+
199+
var ans = [Int](repeating: 1, count: n)
200+
201+
var left = 1
202+
for i in 0..<n {
203+
ans[i] = left
204+
left *= a[i]
205+
}
206+
207+
var right = 1
208+
for i in (0..<n).reversed() {
209+
ans[i] *= right
210+
right *= a[i]
211+
}
212+
213+
return ans
214+
}
215+
}
216+
```
217+
191218
<!-- tabs:end -->
192219

193220
<!-- solution:end -->
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
func constructArr(_ a: [Int]) -> [Int] {
3+
let n = a.count
4+
guard n > 0 else { return [] }
5+
6+
var ans = [Int](repeating: 1, count: n)
7+
8+
var left = 1
9+
for i in 0..<n {
10+
ans[i] = left
11+
left *= a[i]
12+
}
13+
14+
var right = 1
15+
for i in (0..<n).reversed() {
16+
ans[i] *= right
17+
right *= a[i]
18+
}
19+
20+
return ans
21+
}
22+
}

0 commit comments

Comments
 (0)