除自身以外数组的乘积

题目来源:力扣(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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容