链接

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.)

求解

这道题给定我们一个数组,让我们返回一个新数组,对于每一个位置上的数是其他位置上数的乘积,并且限定了时间复杂度 O(n),并且不让我们用除法。如果让用除法的话,那这道题就应该属于 Easy,因为可以先遍历一遍数组求出所有数字之积,然后除以对应位置的上的数字。
但是这道题禁止我们使用除法,那么我们只能另辟蹊径。我们想,对于某一个数字,如果我们知道其前面所有数字的乘积,同时也知道后面所有的数乘积,那么二者相乘就是我们要的结果,所以我们只要分别创建出这两个数组即可,分别从数组的两个方向遍历就可以分别创建出乘积累积数组。参见代码如下:

Java 解法一:

  1. public class Solution {
  2. public int[] productExceptSelf(int[] nums) {
  3. int n = nums.length;
  4. int[] res = new int[n];
  5. int[] fwd = new int[n], bwd = new int[n];
  6. fwd[0] = 1; bwd[n - 1] = 1;
  7. // 当前位置前的之前的乘积
  8. for (int i = 1; i < n; ++i) {
  9. fwd[i] = fwd[i - 1] * nums[i - 1];
  10. }
  11. // 当前位置之后的乘积
  12. for (int i = n - 2; i >= 0; --i) {
  13. bwd[i] = bwd[i + 1] * nums[i + 1];
  14. }
  15. for (int i = 0; i < n; ++i) {
  16. res[i] = fwd[i] * bwd[i];
  17. }
  18. return res;
  19. }
  20. }

我们可以对上面的方法进行空间上的优化,由于最终的结果都是要乘到结果 res 中,所以可以不用单独的数组来保存乘积,而是直接累积到结果 res 中,我们先从前面遍历一遍,将乘积的累积存入结果 res 中,然后从后面开始遍历,用到一个临时变量 right,初始化为1,然后每次不断累积,最终得到正确结果,参见代码如下:

Java 解法二:

  1. public class Solution {
  2. public int[] productExceptSelf(int[] nums) {
  3. int n = nums.length, right = 1;
  4. int[] res = new int[n];
  5. res[0] = 1;
  6. for (int i = 1; i < n; ++i) {
  7. res[i] = res[i - 1] * nums[i - 1];
  8. }
  9. for (int i = n - 1; i >= 0; --i) {
  10. res[i] *= right;
  11. right *= nums[i];
  12. }
  13. return res;
  14. }
  15. }


类似题目:
Trapping Rain Water
Maximum Product Subarray
Paint House II

参考资料:
https://leetcode.com/problems/product-of-array-except-self/
https://leetcode.com/problems/product-of-array-except-self/discuss/65638/My-simple-Java-solution
https://leetcode.com/problems/product-of-array-except-self/discuss/65622/Simple-Java-solution-in-O(n)-without-extra-space-without-extra-space)