码迷,mamicode.com
首页 > 编程语言 > 详细

[LintCode] Product of Array Except Self 除本身之外的数组之积

时间:2016-12-05 01:52:03      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:数组   amp   博客   rand   log   res   param   opera   ati   

 

Given an integers array A.

Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B WITHOUT divide operation.

Example

For A = [1, 2, 3], return [6, 3, 2].

 

LeetCode上的原题,请参见我之前的博客Product of Array Except Self

 

解法一:

class Solution {
public:
    /**
     * @param A: Given an integers array A
     * @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
     */
    vector<long long> productExcludeItself(vector<int> &nums) {
        int n = nums.size();
        vector<long long> fwd(n, 1), bwd(n, 1), res(n);
        for (int i = 0; i < n - 1; ++i) {
            fwd[i + 1] = fwd[i] * nums[i];
        }
        for (int i = n - 1; i > 0; --i) {
            bwd[i - 1] = bwd[i] * nums[i];
        }
        for (int i = 0; i < n; ++i) {
            res[i] = fwd[i] * bwd[i];
        }
        return res;
    }
};

 

解法二:

class Solution {
public:
    /**
     * @param A: Given an integers array A
     * @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
     */
    vector<long long> productExcludeItself(vector<int> &nums) {
        long long n = nums.size(), right = 1;
        vector<long long> res(n, 1);
        for (int i = 1; i < n; ++i) {
            res[i] = res[i - 1] * nums[i - 1];
        }
        for (int i = n - 1; i >= 0; --i) {
            res[i] *= right;
            right *= nums[i];
        }
        return res;
    }
};

 

[LintCode] Product of Array Except Self 除本身之外的数组之积

标签:数组   amp   博客   rand   log   res   param   opera   ati   

原文地址:http://www.cnblogs.com/grandyang/p/6132378.html

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