Skip to content

Commit aae4031

Browse files
authored
Merge pull request #241 from ShawnMa16/master
Update #ProductExceptSelf with a faster speed than 100% Swift online
2 parents 3c42db4 + 5a35725 commit aae4031

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

Array/ProductExceptSelf.swift

+14-15
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,20 @@
77

88
class ProductExceptSelf {
99
func productExceptSelf(_ nums: [Int]) -> [Int] {
10-
var res = Array(repeating: 1, count: nums.count)
11-
var right = 1
12-
13-
guard nums.count > 0 else {
14-
return res
10+
var zeroCount = 0
11+
let total = nums.reduce(1) {
12+
if $1 == 0 {
13+
zeroCount += 1
14+
}
15+
return $0 * ($1 == 0 ? 1 : $1)
1516
}
16-
17-
for i in 1..<nums.count {
18-
res[i] = res[i - 1] * nums[i - 1]
19-
}
20-
for i in (0..<nums.count).reversed() {
21-
res[i] = right * res[i]
22-
right = right * nums[i]
23-
}
24-
25-
return res
17+
if zeroCount > 1 {return nums.map({_ in return 0})}
18+
return nums.map({
19+
if zeroCount == 1 {
20+
return ($0 == 0 ? total : 0)
21+
} else {
22+
return ($0 == 0 ? total : total / $0)
23+
}
24+
})
2625
}
2726
}

0 commit comments

Comments
 (0)