leetcode238——Product of Array Except Self(数组,用空间换时间)

Product of Array Except Self

  Total Accepted: 4824 Total Submissions: 13439My Submissions

 

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

 

Hide Tags
  Array
 
      这道题要求我们求出一个数组中每一个数的除了它本身之外的其它多有数的乘积,所以采用两个另外的数组来存取,vec1【i】为0,1,2.。。。i-1的乘积
vec2【i】为i+1,i+2。。。n-1的乘积,再依次求乘积
#include<iostream>
#include<vector>
using namespace std;


vector<int> productExceptSelf(vector<int>& nums)
{
    vector<int> vec;
    if(nums.empty())
        return vec;
    if(nums.size()==1)
        return nums;
    vector<int> vec1=nums;
    vector<int> vec2=nums;
    int n=nums.size();
    vec1[0]=1;
    int re=1;
    for(int i=0;i<n-1;i++)
    {
        re*=nums[i];
        vec1[i+1]=re;
    }

    vec2[n-1]=1;
    re=1;
    for(int i=n-1;i>0;i--)
    {
        re*=nums[i];
        vec2[i-1]=re;
    }

    for(int i=0;i<n;i++)
    {
        vec.push_back(vec1[i]*vec2[i]);
    }
    return vec;
}
int main()
{
    int ary[10]={1,2,3};
    vector<int> vec(ary,ary+3);

}

 

你可能感兴趣的:(LeetCode)