Skip to content

Latest commit

 

History

History
24 lines (24 loc) · 701 Bytes

2021-3-22-1.md

File metadata and controls

24 lines (24 loc) · 701 Bytes

除自身以外数组的乘积

给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。

class Solution {
    /**
     * 左边乘积 * 右边乘积
     *
     */
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        int left = 1;
        int right = 1;
        for (int i = 0; i < res.length; i++) {
            res[i] = left;
            left *= nums[i];
        }
        for (int i = nums.length - 1; i >= 0; i--) {
            res[i] *= right;
            right *= nums[i];
        }
        return res;
    }
}