238. Product of Array Except Self

来源:互联网 发布:php面向对象 实战项目 编辑:程序博客网 时间:2024/05/18 02:32

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

我的解答:

1.额外空间O(n)  时间复杂度O(1)

2.额外空间O(1)  时间复杂度O(1)

////  main.cpp//  238. Product of Array Except Self////  Created by zjl on 16/6/23.//  Copyright © 2016年 zjl. All rights reserved.//#include <iostream>#include <vector>using namespace std;vector<int> productExceptSelf1(vector<int>& nums) {    int n = nums.size();    vector<int> formbeg(n+1,1);    vector<int> formend(n+1,1);    vector<int> res(n,1);            for(int i = 1; i <= n; i++){        formbeg[i] = formbeg[i-1]*nums[i-1];    }        for(int i = n-1; i >=0; i--){        formend[i] = formend[i+1]*nums[i];    }        for(int j = 0; j < n; j++){        res[j] = formbeg[j] * formend[j+1];    }    return res;}vector<int> productExceptSelf2(vector<int>& nums) {    int n = nums.size();    vector<int>res(n,1);    for(int i = 1; i < n; i++){        res[i] = res[i-1]*nums[i-1];    }    long long t = 1;    for(int j = n-1; j >=0; j--){        res[j] *= t;        t *= nums[j];    }    return res;}int main(int argc, const char * argv[]) {    vector<int> nums = {1,2,3,4};    vector<int> res = productExceptSelf2(nums);    for(int i = 0; i < res.size(); i++)        cout<<res[i] << " ";    cout<<endl;    return 0;}

输入: 1,2,3,4

输出:24 12 8 6 

0 0
原创粉丝点击