美文网首页
除自身以外数组的乘积

除自身以外数组的乘积

作者: Haward_ | 来源:发表于2019-10-15 21:39 被阅读0次

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

示例:

输入: [1,2,3,4]
输出: [24,12,8,6]
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/product-of-array-except-self

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        // temp用来累计nums[i]左边的乘积
        int temp = 1;
        for(int i=0;i<nums.length;i++) {
            res[i] = temp;
            temp *= nums[i];
        }
        // 同理, temp用来累计nums[i]右边的乘积(并且与左边乘积相乘)
        temp = 1;
        for(int i=nums.length-1;i>=0;i--) {
            res[i] *= temp;
            temp *= nums[i];
        }
        return res;
    }
}

相关文章

网友评论

      本文标题:除自身以外数组的乘积

      本文链接:https://www.haomeiwen.com/subject/eveemctx.html