Skip to content

Commit d16fc61

Browse files
committed
Because of The problem statement mentions that don't using divide , but the solution use divide in last line in file, the advantages of the solution is use less space . So I add back solution that do not using divide as before. The time cost is almost same both solution.
1 parent b2e7678 commit d16fc61

File tree

1 file changed

+60
-23
lines changed

1 file changed

+60
-23
lines changed

Diff for: Array/ProductExceptSelf.swift

+60-23
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,63 @@
11
/**
2-
* Question Link: https://leetcode.com/problems/product-of-array-except-self/
3-
* Primary idea: Use two arrays to hold multiplication result from left and right sides
4-
* while iterating the original array
5-
* Time Complexity: O(n), Space Complexity: O(1)
6-
*/
2+
* Question Link: https://leetcode.com/problems/product-of-array-except-self/
3+
* Primary idea: Use two arrays to hold multiplication result from left and right sides
4+
* while iterating the original array
5+
* Time Complexity: O(n), Space Complexity: O(1)
6+
*/
77

88
class ProductExceptSelf {
9-
func productExceptSelf(_ nums: [Int]) -> [Int] {
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)
16-
}
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-
})
25-
}
26-
}
9+
func productExceptSelf(_ nums: [Int]) -> [Int] {
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)
16+
}
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+
})
25+
}
26+
}
27+
28+
29+
30+
31+
/**
32+
* Question Link: https://leetcode.com/problems/product-of-array-except-self/
33+
* Primary idea: Dynamic Programming, track Left and Right product lists at the same time and just use one additional array.The problem statement mentions that using theanswer array doesn't add to the space complexity.
34+
* Time Complexity: O(n), Space Complexity: O(1)
35+
*/
36+
37+
38+
class ProductExceptSelfNotUseDivide{
39+
40+
func productExceptSelf(_ nums: [Int]) -> [Int] {
41+
42+
var arr = Array.init(repeating: 1, count: nums.count)
43+
44+
for i in (0..<(nums.count - 1)).reversed() {
45+
46+
arr[i] = arr[i + 1] * nums[i + 1]
47+
48+
}
49+
50+
var left = 1
51+
for i in 0..<nums.count {
52+
if i == 0 {
53+
arr[i] = left * arr[i]
54+
} else {
55+
left = left * nums[i - 1]
56+
arr[i] = left * arr[i]
57+
}
58+
}
59+
60+
return arr
61+
}
62+
63+
}

0 commit comments

Comments
 (0)