Product of Array Except Self (M)
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
题意
给定一个数组nums,要求返回一个新数组output,满足以下条件:
output[i]=∏j≠inums[j]
output[i] = \prod_{j\not=i}nums[j]
output[i]=j=i∏nums[j]
限制时间复杂度为O(N)O(N)O(N),且不能使用除法。
思路
output[i]相当于在nums中将nums[i]左边所有数和nums[i]右边所有数累乘。因此可以采取类似于动态规划的操作:先从左到右遍历一遍nums,记录当前位置所有左侧数字之积;再从右到左遍历一遍nums,记录当前位置所有右侧数字之积,将两者相乘后得到的就是output。可以只使用一个output数组来达到O(1)O(1)O(1)的空间复杂度。
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| nums | 1 | 2 | 3 | 4 |
| 左右遍历 | 1 | 1 | 2 | 6 |
| 右左遍历 | 24 | 12 | 4 | 1 |
| Output | 24 | 12 | 8 | 6 |
代码实现
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] output = new int[nums.length];
int leftProduct = 1;
for (int i = 0; i < nums.length; i++) {
output[i] = i == 0 ? 1 : (leftProduct *= nums[i - 1]);
}
int rightProduct = 1;
for (int i = nums.length - 1; i >= 0; i--) {
output[i] = output[i] * (i == nums.length - 1 ? 1 : (rightProduct *= nums[i + 1]));
}
return output;
}
}
本文介绍了一种在O(n)时间复杂度内解决数组产品问题的方法,即求解除自身外数组中所有元素的乘积。通过两次遍历,首先计算每个元素左侧所有元素的乘积,然后计算每个元素右侧所有元素的乘积,最终得到目标数组。此方法避免了使用除法运算,同时达到了O(1)的空间复杂度。
6138

被折叠的 条评论
为什么被折叠?



