238. 除自身以外数组的乘积

执行用时:160 ms, 在所有 Swift 提交中击败了100.00%的用户
内存消耗:19.2 MB, 在所有 Swift 提交中击败了100.00%的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
let n = nums.count
var res = [Int]()
var L = [Int].init(repeating: 1, count: n)
var R = [Int].init(repeating: 1, count: n)
for i in 1 ..< n {
L[i] = L[i-1] * nums[i-1]
}
for j in (0 ..< n-1).reversed() {
R[j] = R[j+1] * nums[j+1]
}
for i in 0 ..< n {
res.append(L[i] * R[i])
}
return res
}
}

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] L = new int[n];
int[] R = new int[n];
int[] res = new int[n];
L[0] = 1;
for (int i = 1; i < n; i++) {
L[i] = L[i-1] * nums[i-1];
}
R[n-1] = 1;
for (int i = n-2; i >= 0; i--) {
R[i] = R[i+1] * nums[i+1];
}
for (int i = 0; i < n; i++) {
res[i] = L[i] * R[i];
}
return res;
}
}

238. 除自身以外数组的乘积
https://pisces34.github.io/2021/10/10/leetcode/238/
发布于
2021年10月10日
许可协议