LeetCode-Product of Array Except Self

61 篇文章 10 订阅
37 篇文章 0 订阅

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

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:

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


自己没倒腾出来,确实挺难想的,但是当得知其中的奥秘时,不时感觉此算法真是妙。

题目大致意思就是求一个output数组,output[i]为数组nums数组除nums[i]之外数字的所有乘积,比如:

Input : [1, 2, 3, 4, 5]
Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)]
      = [120, 60, 40, 30, 24]
要求不用除法,时间复杂度O(n)

解题思路基于以下集合

{              1,         a[0],    a[0]*a[1],    a[0]*a[1]*a[2],  }
{ a[1]*a[2]*a[3],    a[2]*a[3],         a[3],                 1,  }
很显然,这两个集合都可以在O(n)的时间复杂度求得,之后两个集合对应位置相乘即为所得。是不是很妙?

空间复杂度为O(n)的实现:

public int[] productExceptSelf(int[] nums) {
        int[] productBelow = new int[nums.length];
        int n = 1;
        for (int i = 0; i < nums.length; i++) {
        	productBelow[i] = n;
        	n *= nums[i];
        }
        
        int[] productAbove = new int[nums.length];
        n = 1;
        for (int i = nums.length-1; i >= 0; i--) {
        	productAbove[i] = n;
        	n *= nums[i];
        }
        
        int[] output = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
        	output[i] = productAbove[i] * productBelow[i];
        }
        return output;
    }
但是,如果要求是O(1)的空间复杂度呢?只需要把最后两步合二为一即可:
int[] output = new int[nums.length];
        int n = 1;
        for (int i = 0; i < nums.length; i++) {
        	output[i] = n;
        	n *= nums[i];
        }
        
        n = 1;
        for (int i = nums.length-1; i >= 0; i--) {
        	output[i] *= n;
        	n *= nums[i];
        }
        return output;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值