码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_238. Product of Array Except Self_思维

时间:2018-12-08 21:13:49      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:pts   span   color   根据   i++   tmp   out   需要   blank   

https://leetcode.com/problems/product-of-array-except-self/

给一个vector<int> nums,输出一个vector<int> res,res[i]为nums中除去nums[i]以外所有数的乘积。且不能使用除法运算,时间复杂度为O(n),空间复杂度尽量小。

思路:首先从左往右遍历,对任意i,可以求得nums[0,i-1]的乘积;再从右往左遍历,对任意i,可以求得nums[i+1,n-1]的乘积。根据题意,只需要额外需要O(1)的空间复杂度。

class Solution
{
public:
    vector<int> productExceptSelf(vector<int>& nums)
    {
        int len = nums.size();
        vector<int> res = nums;
        res[0]=1;
        cout<<res[0]<<endl;
        for(int i=1; i<len; i++)
            res[i] = res[i-1] * nums[i-1];
        int tmp = 1;
        for(int i=len-1; i>=0; i--)
        {
            res[i] = res[i]*tmp;
            tmp *= nums[i];
        }
        return res;
    }
};

 

leetcode_238. Product of Array Except Self_思维

标签:pts   span   color   根据   i++   tmp   out   需要   blank   

原文地址:https://www.cnblogs.com/jasonlixuetao/p/10088848.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!