首页 > 其他 > 详细

leetcode_238. Product of Array Except Self_思维

时间:2018-12-08 21:02:22      阅读:182      评论:0      收藏:0      [点我收藏+]

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_思维

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

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