leetcode 238. Product of arrays other than themselves

 An integer array of length  n  ,  numswhere  n  > 1, returns an array   equal to the product of all elements except in .outputoutput[i]numsnums[i]

Solve this problem without division and in O( n ).

For example, enter  [1,2,3,4], return  [24,12,8,6].

Advanced:
Can you solve this problem in constant space complexity? (Note: For the purposes of space complexity analysis, the output array is not considered extra space.)

 

 

Problem solving ideas:

  1. Use two arrays left, right to store the product from left to right and the product from right to left
 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 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324962804&siteId=291194637