赞
踩
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> prefix;
int size = nums.size();
prefix.push_back(1); // 初值赋为1很关键
for (int i = 1; i < size; i++) {
int temp = prefix[i-1]*nums[i-1];
prefix.push_back(temp);
}
int templast = nums[size-1]; // 这里要记录即将被修改的nums数组值
nums[size-1]=1;
for (int i = 1; i < size; i++) {
int temp = nums[size-i]*templast;
templast = nums[size-i-1]; // 更新templast的值
nums[size-i-1] = temp;
}
for (int i = 0; i < size; i++) {
prefix[i] *= nums[i];
}
return prefix;
}
};
int main() {
Solution s;
vector<int> temp;
int n;
cin >> n;
cout << endl << endl;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
temp.push_back(x);
}
vector<int> printarray = s.productExceptSelf(temp);
for (int i = 0; i < printarray.size(); i++) {
cout << printarray[i] << " ";
}
cout << endl;
getchar();
getchar();
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。