您的位置:首页 > 其它

算法设计与应用基础:第一周(3)

2017-02-23 22:24 405 查看


238. Product of Array Except Self

Add to List

Description Submission Solutions

Total Accepted: 84193
Total Submissions: 176822
Difficulty: Medium
Contributors: Admin

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

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n=nums.size();
int fromBegin=1;
int fromLast=1;
vector<int> res(n,1);

for(int i=0;i<n;i++){
res[i]*=fromBegin;
fromBegin*=nums[i];

}
//for(int i=0;i<n;i++)
//cout<<res[i]<<endl;
for(int i=n-1;i>=0;i--)
{
res[i]*=fromLast;
fromLast*=nums[i];
}
//for(int i=0;i<n;i++)
//cout<<res[i]<<endl;
return res;
}
};


解题思路:主要在于算法中的两层循环,思路借鉴了博客一位大神对于算数组前n项积的方法。第一层循环:利用哨兵值Fromfirst每次res[i]累乘Fromfirst相当于累乘nums[i]之前的数组累积;第二层循环:res[i]每次累乘Fromlast相当于累乘nums[i]之后的数组累积;两层循环之后可得到正确的res值
res[i]*=fromBegin;
fromBegin*=nums[i];
第一行res[i]累乘fromBegin,第二行fromBegin累乘nums[i]以达到res[i]累乘之前所有的目的





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: