leetcode 238. Product of Array Except Self

33 篇文章 0 订阅
30 篇文章 0 订阅

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input: [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

tag: array

method 1

动态规划,使用两个动态数组。leftDp[i] 表示i左边的数的乘积,rightDp[i] 表示i右边的数的乘积,那么res[i] = leftDp[i] * leftDp[i]

public int[] productExceptSelf1(int[] nums) {
    int i, j;

    int[] leftDP = new int[nums.length];
    int[] rightDP = new int[nums.length];

    int leftProduct = 1;
    int rightProduct = 1;
    leftDP[0] = 1;
    rightDP[nums.length-1] = 1;

    for (i = 1, j = nums.length-2; i < nums.length; i++,j--) {
        leftProduct *= nums[i-1];
        rightProduct *= nums[j+1];
        leftDP[i] = leftProduct;
        rightDP[j] = rightProduct;
    }

    int[] answer = new int[nums.length];
    for (int k = 0; k < nums.length; k++) {
        answer[k] = leftDP[k]*rightDP[k];
    }

    return answer;
}

method 2

观察method 1,其实不算严格意义上的动态规划,method 1使用了两个额外的数组,深入考虑我们发现,其实res[i] 相当于乘了左边的乘积之后乘右边的乘积,method 1是同时乘,这里可以把这两个过程分开,在一次循环中遍历两次

public int[] productExceptSelf2(int[] nums) {
    int i, j;
    int leftProduct = 1;
    int rightProduct = 1;

    int[] answer = new int[nums.length];

    for (int k = 0; k < answer.length; k++) {
        answer[k] = 1;
    }

    for (i = 1, j = nums.length-2; i < nums.length; i++,j--) {
        leftProduct *=nums[i-1];
        rightProduct *= nums[j+1];

        answer[i] *= leftProduct;
        answer[j] *= rightProduct;
    }

    return answer;
}

method 3

相当于将method 2 中的一个循环拆成两个循环

public int[] productExceptSelf3(int[] nums) {
    int[] result = new int[nums.length];
    for (int i = 0, tmp = 1; i < nums.length; i++) {
        result[i] = tmp;
        tmp *= nums[i];
    }
    for (int i = nums.length - 1, tmp = 1; i >= 0; i--) {
        result[i] *= tmp;
        tmp *= nums[i];
    }
    return result;
}

summary:

  1. 优化时考虑能否将诸如储存累乘结果的数组简化为一个变量
  2. 一次循环两次遍历
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值