您的位置:首页 > 编程语言 > C语言/C++

238. Product of Array Except Self

2016-06-23 21:33 344 查看
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 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ array