Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Question 1: without division. We can simply compose left\right accumulated product arrays:

typedef long long LL;
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) 
    {
        size_t len = nums.size();
        vector<LL> left(len), right(len);
        left[0] = nums[0];
        for (int i = 1; i < len - 1; i++)
            left[i] = nums[i] * left[i - 1];
        right[len - 1] = nums.back();
        for (int i = len - 2; i > 0; i--)
            right[i] = nums[i] * right[i + 1];

        vector<int> ret(len);
        for (int i = 0; i < len; i++)
        {
            LL l = (!i) ? 1 : left[i - 1];
            LL r = (i == len - 1) ? 1 : right[i + 1];
            ret[i] = l * r;
        }
        return ret;
    }
};

Follow-up question: constant space - we can remove right<int>

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums)
    {
        size_t len = nums.size();
        vector<int> ret(len);
        ret[0] = nums[0];
        for (int i = 1; i < len - 1; i++)
            ret[i] = nums[i] * ret[i - 1];
        
        int right = 1;
        for (int i = len - 1; i >=0; i --)
        {
            ret[i] = (i > 0 ? ret[i - 1] : 1) * right;
            right *= nums[i];
        }
        return ret;
    }
};

Third solution: sliding window, but may not be quite optimized if there's 0

typedef long long LL;
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) 
    {
        size_t len = nums.size();        
        vector<int> ret(len);

        int slot = len - 1;
        
        LL pro = 1;
        for (int i = 0; i < len - 1; i++)
            pro *= nums[i];
        
        for (int i = 0; i < len; i++) // start inx
        {
            ret[slot] = pro;
            if (nums[i]!=0) pro /= nums[i];
            else
            {
                pro = 1;
                for (int j = i + 1; j < i + 1 + len - 2; j++)
                    pro *= nums[j % len];
            }
            pro *= nums[slot];
            slot = (slot + 1) % len;            
        }

        return ret;
    }
};
posted on 2015-07-16 13:21  Tonix  阅读(178)  评论(0编辑  收藏  举报