Leetcode 238. Product of Array Except Self

本文介绍了一种高效算法,用于求解数组中每个元素等于该数组其他所有元素的乘积的问题,避免了使用除法操作。通过两次遍历数组分别计算左侧乘积和右侧乘积来实现。

http://stackoverflow.com/questions/2680548/given-an-array-of-numbers-return-array-of-products-of-all-other-numbers-no-div

/**
 * The product of an index equals to the product left to the indx times the product right to the index.
 * e.g. [1, 2, 3, 4]
 * Calculate the product left to an index i (from left to right)
 * A = [1, 1, 2, 6] the product left to index 0 is 1
 * Calculate the product right to an index i (from right to left)
 * B = [24, 12, 4, 1] 
 * The result would be 
 * A * B = [24, 12, 8, 6]
 */ 
public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        res[0] = 1;
        
        // calculate the left product 
        for (int i=1; i<nums.length; i++)
            res[i] = nums[i-1] * res[i-1];
        System.out.println(res[1]);
        // use a variable to save the right product
        int rp = 1; 
        for (int i=nums.length-1; i>-1; i--) {
            res[i] *= rp;
            rp     *= nums[i];
        }
        
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值