[LeetCode] 238. Product of Array Except Self
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) 时间复杂度内完成此题。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/product-of-array-except-self
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
题意是给一个数组,请输出一个等长的数组,res[i] 位上存的是 input 数组除了 i 位其他所有数字的乘积。
注意这个题不能用除法,如果用除法会很简单。思路是我们创建一个和 input 数组等长的 res 数组记录结果,对于在 i 位上的数字,在 res[i] 上存住从左往右把之前每个数字相乘的乘积 * 从右向左在 i 之后每个数字相乘的乘积。注意左边和右边的代码稍有不同,需要多体会。
复杂度
时间O(n)
空间O(n) - output
代码
Java实现
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int left = 1;
for (int i = 0; i < n; i++) {
res[i] = left;
left *= nums[i];
}
int right = 1;
for (int i = n - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
}
JavaScript实现
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function (nums) {
var left = 1;
var product = [];
for (let num of nums) {
product.push(left);
left = left * num;
}
var right = 1;
for (var i = nums.length - 1; i >= 0; i--) {
product[i] *= right;
right = right * nums[i];
}
return product;
};