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

除自身以外数组的乘积

作者: 二进制的二哈 | 来源:发表于2019-12-26 18:58 被阅读0次

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

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

示例:

输入: [1,2,3,4]
输出: [24,12,8,6]

说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。

进阶:
你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)。

动态规划解法(需要额外空间):

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] dpLeft = new int[nums.length];
        int[] dpRight = new int[nums.length];
        dpLeft[0] = 1;
        for(int i=1;i<nums.length;i++){
            dpLeft[i] = dpLeft[i-1]*nums[i-1];
        }
        dpRight[nums.length-1] = 1;
        for(int i=nums.length-2;i>=0;i--){
            dpRight[i] = dpRight[i+1]*nums[i+1];
        }
        int[] ans = new int[nums.length];
        for(int i=0;i<nums.length;i++){
            ans[i] = dpLeft[i]*dpRight[i];
        }
        return ans;
    }
}

相关文章

网友评论

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

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