leetcode 238. 除自身以外数组的乘积

一个长度为 n 的整形数组nums,其中 n > 1,返回一个数组 output ,其中 output[i] 等于nums中除nums[i]以外所有元素的乘积。

不用除法 且在O(n)内解决这个问题。

例如,输入 [1,2,3,4],返回 [24,12,8,6]

进阶:
你可以在常数空间复杂度内解决这个问题吗?(注意:出于空间复杂度分析的目的,输出数组不被视为额外空间。)

解题思路:

  1. 用两个数组left,right来保存从左到右的乘积,和从右到左的乘积
 1 class Solution {
 2 public:
 3     vector<int> productExceptSelf(vector<int>& nums) {
 4         int len = nums.size();
 5         int *left = new int[len], *right = new int [len];
 6         left[0] = nums[0]; right[len-1] = nums[len-1];
 7         for(int i = 1; i < len-1; i++) {
 8             left[i] = left[i-1]*nums[i];
 9             right[len-i-1] = right[len-i]*nums[len-i-1];
10         }
11         vector<int> ans;
12         ans.push_back(right[1]);
13         for(int i = 1; i < len-1; i++) ans.push_back(left[i-1]*right[i+1]);
14         ans.push_back(left[len-2]);
15         return ans;
16     }
17 };

猜你喜欢

转载自www.cnblogs.com/mr-stn/p/8951354.html