Product of Array Except Self

题目:

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

解析:

开始连题都没读懂,关键是product是乘积的意思。题目不让用除法(division),而且在O(n)完成

这题不会做,别人思路:

1. 使用辅助空间

为方便理解,使用两个与输入数组同等大小的辅助数组

首先,从前到后扫描数组,一个数组[i]存储的是除了当前元素外的所有前面元素的乘积;

然后,从后到前扫描数组,另一个数组[i]存储的是除了当前元素外的所有后面元素的乘积。

最后将这两个数组的对应位置的元素相乘即可。

优化后可以省略一个数组和一遍扫描。

比如[1,2,3,4]

数字左边乘积的数组为:[1,1,2,6]  左边或者右边没有的置为1

数字右边乘积的数组为:[24,12,4,1]

然后这个两个数组对应的乘积就是结果:

 1 class Solution {
 2 public:
 3     vector<int> productExceptSelf(vector<int>& nums) {
 4         vector<int> tmp(nums.size(),1);
 5         vector<int> res(nums.size(),1);
 6         for(int i = 1;i<tmp.size();i++)
 7         {
 8             tmp[i] = tmp[i-1] * nums[i-1];
 9             res[i] = tmp[i];
10         }
11         tmp[tmp.size()-1] = 1;
12         for(int i = tmp.size()-2;i >= 0;i--)
13         {
14             tmp[i] = tmp[i+1] * nums[i+1];
15             res[i] = tmp[i] * res[i];
16         }
17         return res;
18     }
19 };
原文地址:https://www.cnblogs.com/raichen/p/4935925.html