题目:
Given an array nums
of n integers where n > 1, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Example:
Input:[1,2,3,4]
Output:[24,12,8,6]
Note: Please solve it without division and in O(n).
翻译:
给定一个含有n个数字的数组nums,其中n>1,返回一个output数组其中output[i]等于nums中除了nums[i]之外的所有元素的乘积。
例子:
输入:[1,2,3,4]
输出:[24,12,8,6]
注意: 请解决这个问题不用除法,并且控制时间复杂度在O(n)范围。
思路:
http://www.cnblogs.com/grandyang/p/4650187.html 中说的很明确,解法相当巧妙,用某个数字前面所有数字的乘积,同时也知道它后面所有的数乘积,那么二者相乘就是我们要的结果。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> forward(n, 1), backward(n, 1), result(n);
for (int i = 0; i < n - 1; i++) {
forward[i + 1] = forward[i] * nums[i];
}
for (int i = n - 1; i > 0; i--) {
backward[i - 1] = backward[i] * nums[i];
}
for (int i = 0; i < n; i++) {
result[i] = forward[i] * backward[i];
}
return result;
}
};
int main()
{
Solution s;
vector<int> nums = { 1,2,3,4 };
vector<int> result = s.productExceptSelf(nums);
for (int i = 0; i < result.size(); i++) {
cout << result[i] << " ";
}
return 0;
}