238. Product of Array Except Self

Posted 会咬人的兔子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了238. Product of Array Except Self相关的知识,希望对你有一定的参考价值。

238. Product of Array Except Self

  • Total Accepted: 80998
  • Total Submissions: 171009
  • Difficulty: Medium
  • Contributors: Admin

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

Solution1:

Use two vectors to record the product of numbers befor/after the current number.

The result[i] is the product of  fwd[i] * bwd[i]

 1 class Solution {
 2 public:
 3     vector<int> productExceptSelf(vector<int>& nums) {
 4         int n = nums.size();
 5         vector<int> fwd(n, 1);
 6         vector<int> bwd(n, 1);
 7         vector<int> res(n);
 8         //forward
 9         for(int i = 0; i < n - 1; i++){
10             fwd[i + 1] = fwd[i] * nums[i];
11         }
12         //backward
13         for(int i = n - 1; i > 0; i--){
14             bwd[i - 1] = bwd[i] * nums[i];
15         }
16         for(int i = 0; i < n; i++){
17             res[i] = fwd[i] * bwd[i];
18         }
19         return res;
20     }
21 };

Solution 2:

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

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

以上是关于238. Product of Array Except Self的主要内容,如果未能解决你的问题,请参考以下文章

238. Product of Array Except Self

LeetCode OJ 238. Product of Array Except Self 解题报告

238. Product of Array Except Self

238. Product of Array Except Self

238. Product of Array Except Self

238. Product of Array Except Self