Medium
题目描述
给你一个整数数组 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 <= 10^5-30 <= nums[i] <= 30- 保证 数组
nums之中任意元素的全部前缀元素和后缀元素的乘积都在 32 位 整数范围内
进阶: 你可以在 O(1) 的额外空间复杂度内完成这个题目吗?( 输出数组不被计算在额外空间内。)
解题思路
这道题要求在不使用除法的情况下,计算除自身以外所有元素的乘积。核心思路是利用前缀积和后缀积。
基本思路: 对于位置 i 的结果,等于该位置左侧所有元素的乘积 × 右侧所有元素的乘积。我们可以分两步来实现:
- 第一遍遍历:计算每个位置左侧元素的乘积(前缀积)
- 第二遍遍历:计算每个位置右侧元素的乘积(后缀积),并与前缀积相乘得到最终结果
优化空间复杂度: 为了达到 O(1) 额外空间,我们可以:
- 先用结果数组存储前缀积
- 然后从右往左遍历,用一个变量维护后缀积,边计算边更新结果数组
算法步骤:
- 第一次遍历:
result[i]存储nums[0]到nums[i-1]的乘积 - 第二次从右往左遍历:用变量
rightProduct维护右侧乘积,将result[i]乘以rightProduct
这种方法时间复杂度 O(n),空间复杂度 O(1)(不计输出数组)。
代码实现
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> result(n, 1);
// 第一遍:计算左侧乘积
for (int i = 1; i < n; i++) {
result[i] = result[i - 1] * nums[i - 1];
}
// 第二遍:计算右侧乘积并更新结果
int rightProduct = 1;
for (int i = n - 1; i >= 0; i--) {
result[i] *= rightProduct;
rightProduct *= nums[i];
}
return result;
}
};
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
result = [1] * n
# 第一遍:计算左侧乘积
for i in range(1, n):
result[i] = result[i - 1] * nums[i - 1]
# 第二遍:计算右侧乘积并更新结果
right_product = 1
for i in range(n - 1, -1, -1):
result[i] *= right_product
right_product *= nums[i]
return result
public class Solution {
public int[] ProductExceptSelf(int[] nums) {
int n = nums.Length;
int[] result = new int[n];
// 第一遍:计算左侧乘积
result[0] = 1;
for (int i = 1; i < n; i++) {
result[i] = result[i - 1] * nums[i - 1];
}
// 第二遍:计算右侧乘积并更新结果
int rightProduct = 1;
for (int i = n - 1; i >= 0; i--) {
result[i] *= rightProduct;
rightProduct *= nums[i];
}
return result;
}
}
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
const n = nums.length;
const result = new Array(n).fill(1);
// 第一遍:计算左侧乘积
for (let i = 1; i < n; i++) {
result[i] = result[i - 1] * nums[i - 1];
}
// 第二遍:计算右侧乘积并更新结果
let rightProduct = 1;
for (let i = n - 1; i >= 0; i--) {
result[i] *= rightProduct;
rightProduct *= nums[i];
}
return result;
};
复杂度分析
| 复杂度类型 | 复杂度 | 说明 |
|---|---|---|
| 时间复杂度 | O(n) | 需要遍历数组两次,每次 O(n) |
| 空间复杂度 | O(1) | 除了输出数组外,只使用常量额外空间 |