Product of Array Except Self
Total Accepted: 26470 Total Submissions: 66930 Difficulty: Medium
Given an array of n integers where n > 1, nums
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
限定了不能用除法,和时间复杂度。
但Follow up我没太懂,是不允许申请额外的空间吗?
这次本来想用位运算中的异或运算写,但是发现那样有固有缺陷——对负数不起效果。而且越改越臃肿。
最后在Discuss中找到一个好方法, 这个方法申请了额外的数组。
优点:
- 得到数组中新的一个数字时,借助了上一位,从而不用再次遍历整个数组
- 方法很巧妙
下面是看完解答后自己写的:
Java语言写的
1 public class Solution { 2 public int[] productExceptSelf(int[] nums) { 3 int[] res = new int[nums.length]; 4 res[0] = 1; 5 for (int i = 1; i < nums.length; i++) { 6 res[i] = res[i - 1] * nums[i - 1]; 7 } 8 int right = 1; 9 for (int i = nums.length - 1; i >= 0; i--) { 10 res[i] *= right; 11 right *= nums[i]; 12 } 13 return res; 14 } 15 }