[LeetCode] 238. Product of Array Except Self
Posted C·Moriarty
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 238. 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]
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.)
题意:给一数组,输出除了这个数字以外所有数字的乘积
注意,不用除法(其实你用了它也不会报错),尽可能在常数级的空间内解决问题。
如果用除法大家肯定都会,不用除法,而且要在O(n)的条件下完成。
我们会到问题,关键有两点,数组和乘积,这个位置的答案可以看作是它左边所有数字的积乘以它右边数字的积
那么我们就需要额外开两个数组,分别从左向右 从右向左乘一次,最后在乘一次即可
class Solution { public int[] productExceptSelf(int[] nums) { int[] left = new int[nums.length]; int[] rigth = new int[nums.length]; int[] res = new int[nums.length]; left[0] = nums[0]; rigth[nums.length - 1] = nums[nums.length - 1]; for (int i = 1; i < nums.length; i++) { left[i] = left[i - 1] * nums[i]; } for (int i = nums.length - 2; i >= 0; i--) { rigth[i] = rigth[i + 1] *nums[i]; } for (int i = 1; i < nums.length - 1 ; i++) { res[i] = rigth[i + 1] * left[i - 1]; } res[0] = rigth[1]; res[nums.length - 1] = left[nums.length - 2]; return res; } }
哈哈,这不满足常数空间的要求(也可以说就是O(1)空间的要求)
不能额外开空间,所以我们优化一下,一边计算一边记录
从右向左的,我们保存到res里,从左向右的,我们用一个int代替就行了(这样不会影响res中没有用的元素)
class Solution { public int[] productExceptSelf(int[] nums) { int[] res = new int[nums.length]; res[nums.length - 1] = nums[nums.length - 1]; for (int i = nums.length - 2; i >= 0; i--) { res[i] = res[i + 1] *nums[i]; } res[0] = res[1]; int mix = nums[0]; for (int i = 1; i < nums.length - 1; i++) { res[i] = mix * res[i + 1]; mix *= nums[i]; } res[nums.length - 1] = mix; return res; } }
以上是关于[LeetCode] 238. Product of Array Except Self的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 238. Product of Array Except Self
238. [LeetCode] Product of Array Except Self
leetcode_238. Product of Array Except Self_思维
LeetCode 238 Product of Array Except Self(除自身外数组其余数的乘积)