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.)
思路分析:如果直接暴力搜索,时间复杂度太高,所以这里采用从前到后与从后到前两次遍历数组,O(n)的时间复杂度,O(n)的空间复杂度
代码如下:
1 class Solution { 2 public: 3 vector<int> productExceptSelf(vector<int>& nums) { 4 //暴力搜索复杂度是O(N^2) 肯定不是好方法,按照题目中的要求,应当可以实现O(n)的时间复杂度 5 //有一种思路很巧,需要遍历两边数组,一遍记录该数(不含)之前的所有数字乘积 6 //第二遍在此基础之上记录该数之后所有数字的乘积 7 int len = nums.size(); 8 vector<int> res(len,1); 9 for (int i = 1; i < len; i++) 10 res[i] = res[i - 1] * nums[i - 1]; 11 int temp = nums[len - 1]; 12 for (int i = len-2; i >=0; i--) 13 { 14 res[i] = res[i] * temp; 15 temp *= nums[i]; 16 } 17 18 /*int temp = 1; 19 for (int i=k-1;i>=0;i--){ 20 res[i]=res[i]*temp; 21 temp*=nums[i]; 22 } 23 return res;*/ 24 return res; 25 } 26 };