首页 > 其他 > 详细

[leetcode] Product of Array Except Self

时间:2015-07-23 00:45:53      阅读:114      评论:0      收藏:0      [点我收藏+]

(1) 预处理出所有数的乘积,然后每次去除nums[i],可以得到正确的答案数组,但是题目中明确写明without division .,不可行。

(2) 预处理出前n项的乘积,放到temp数组中,然后倒着遍历,为了节约空间,我们使用一个Cur变量记录当前后面的乘积。

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int len=nums.size();
         vector<int> temp(len,0);//必须指定合适的大小 
        temp[0]=1;
        for(int i=1;i<len;i++)
        temp[i]=temp[i-1]*nums[i-1];//预处理前n项积
        int Cur=1;
		for(int i=len-1;i>=0;i--)
		{
			temp[i]*=Cur; //节省空间 
			Cur*=nums[i];
		} 
		return temp;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

[leetcode] Product of Array Except Self

原文:http://blog.csdn.net/nk_test/article/details/47011431

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!