Leetcode 238. Product of Array Except Self

来源:互联网 发布:非诚勿扰网络播出时间 编辑:程序博客网 时间:2024/04/20 09:14

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;    }}

0 0