Given an integer array nums
, return an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
.
The product of any prefix or suffix of nums
is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n)
time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4] Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]
Constraints:
2 <= nums.length <= 105
-30 <= nums[i] <= 30
- The product of any prefix or suffix of
nums
is guaranteed to fit in a 32-bit integer.
Follow up: Can you solve the problem in O(1)
extra space complexity? (The output array does not count as extra space for space complexity analysis.)
给你一个整数数组 nums
,返回 数组 answer
,其中 answer[i]
等于 nums
中除 nums[i]
之外其余各元素的乘积 。
题目数据 保证 数组 nums
之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。
请不要使用除法,且在 O(n)
时间复杂度内完成此题。
示例 1:
输入: nums =[1,2,3,4]
输出:[24,12,8,6]
示例 2:
输入: nums = [-1,1,0,-3,3] 输出: [0,0,9,0,0]
提示:
2 <= nums.length <= 105
-30 <= nums[i] <= 30
- 保证 数组
nums
之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内
进阶:你可以在 O(1)
的额外空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
Language | Runtime | Memory | Submission Time |
---|---|---|---|
typescript | 124 ms | 66.6 MB | 2023/03/25 19:57 |
function productExceptSelf(nums: number[]): number[] {
const ans: number[][] = new Array(nums.length).fill([]).map(i => [0, 0]);
let acc = 1;
for (let i = 0; i < nums.length; ++i) {
ans[i][0] = acc * nums[i];
acc = ans[i][0];
}
acc = 1;
for (let i = nums.length - 1; i > 0; --i) {
ans[i][1] = acc * nums[i];
acc = ans[i][1];
}
return ans.map((i, idx) => {
if (idx === 0) {
return ans[1][1];
}
if (idx === nums.length - 1) {
return ans[idx - 1][0];
}
return ans[idx-1][0] * ans[idx+1][1];
})
};
思路:
计算nums[i]
左右累乘的数组乘积,再遍历一遍即可。
空间复杂度为O(n)
。
function productExceptSelf(nums: number[]): number[] {
const ans: number[][] = new Array(nums.length).fill([]).map(i => [0, 0]);
let acc = 1;
for (let i = 0; i < nums.length; ++i) {
ans[i][0] = acc * nums[i];
acc = ans[i][0];
}
acc = 1;
for (let i = nums.length - 1; i > 0; --i) {
ans[i][1] = acc * nums[i];
acc = ans[i][1];
}
return ans.map((i, idx) => {
if (idx === 0) {
return ans[1][1];
}
if (idx === nums.length - 1) {
return ans[idx - 1][0];
}
return ans[idx-1][0] * ans[idx+1][1];
})
};