【LeetCode】238. Product of Array Except Self 除自身以外数组的乘积(Medium)(JAVA)

【LeetCode】238. Product of Array Except Self 除自身以外数组的乘积(Medium)(JAVA)

题目地址: https://leetcode.com/problems/product-of-array-except-self/

题目描述:

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]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.

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

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

题目大意

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

提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。

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

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

解题方法

  1. 这一题主要难的是不能使用除法,那就只能用乘法,而且时间复杂度为 O(n),空间复杂度除了输出数组,也需要为 O(1)
  2. 只能用除法的话,就用乘法,把当前元素左边的所有元素乘起来 * 右边的所有元素乘起来
  3. 左边的所有元素乘起来需要一个数组,右边乘起来也需要一个数组,但是只能用一个数组,该怎么办?
  4. 因为右边的元素相乘不需要保留结果,所以可以用一个常数替换,不用数组也行
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            if (i == 0) {
                res[i] = nums[i];
            } else {
                res[i] = res[i - 1] * nums[i];
            }
        }
        int right = 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (i == 0) {
                res[i] = right;
            } else {
                res[i] = res[i - 1] * right;
            }
            right *= nums[i];
        }
        return res;
    }
}

执行耗时:2 ms,击败了49.20% 的Java用户
内存消耗:49.1 MB,击败了25.80% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值