【LeetCode】238. Product of Array Except Self 除自身以外数组的乘积(Medium)(JAVA)
题目地址: https://leetcode.com/problems/product-of-array-except-self/
题目描述:
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]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
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.)
题目大意
给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。
提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
进阶:
你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
解题方法
- 这一题主要难的是不能使用除法,那就只能用乘法,而且时间复杂度为 O(n),空间复杂度除了输出数组,也需要为 O(1)
- 只能用除法的话,就用乘法,把当前元素左边的所有元素乘起来 * 右边的所有元素乘起来
- 左边的所有元素乘起来需要一个数组,右边乘起来也需要一个数组,但是只能用一个数组,该怎么办?
- 因为右边的元素相乘不需要保留结果,所以可以用一个常数替换,不用数组也行
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (i == 0) {
res[i] = nums[i];
} else {
res[i] = res[i - 1] * nums[i];
}
}
int right = 1;
for (int i = nums.length - 1; i >= 0; i--) {
if (i == 0) {
res[i] = right;
} else {
res[i] = res[i - 1] * right;
}
right *= nums[i];
}
return res;
}
}
执行耗时:2 ms,击败了49.20% 的Java用户
内存消耗:49.1 MB,击败了25.80% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)