leetcode--Product of Array Except Self

本文解决了一个数组问题,即计算一个数组中除当前元素外其余元素的乘积,要求时间复杂度为O(n)且不使用除法。通过使用辅助数组记录前后元素的乘积来达到目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.)


题意:给定一个数组,返回一个结果数组。要求结果数组中的每个元素,等于原数组中的该位置以外的元素的乘积。

例如{1,2,3,4},1位置上的,为2*3*4,那么结果数组的0位就是24

要求不能使用除法,并且时间复杂度为O(n)

你能在常数空间实现吗?output[]数组的空间不计算在内

分类:数组


解法1:解法有点巧妙。使用一个数组,保存元素组某位置,例如i,保存i前的所以元素的乘积

另外一个数组,保存i后所有元素的乘积

最后这两个数组相乘

[java]  view plain  copy
  1. public class Solution {  
  2.     public int[] productExceptSelf(int[] nums) {  
  3.         int len = nums.length;  
  4.         int[] output = new int[len];  
  5.         int[] helper = new int[len];  
  6.         output[0] = 1;  
  7.         helper[len-1] = 1;  
  8.         for(int i=1;i<len;i++){//计算i之前的乘积  
  9.             output[i] = nums[i-1]*output[i-1];  
  10.         }  
  11.         for(int i=len-2;i>=0;i--){//计算i之后的乘积  
  12.             helper[i] = nums[i+1]*helper[i+1];  
  13.         }  
  14.         for(int i=0;i<len;i++){  
  15.             output[i] = output[i]*helper[i];  
  16.         }  
  17.         return output;  
  18.     }  
  19. }  

优化一下代码:

[java]  view plain  copy
  1. public class Solution {  
  2.     public int[] productExceptSelf(int[] nums) {  
  3.         int len = nums.length;  
  4.         int[] output = new int[len];  
  5.         int[] helper = new int[len];  
  6.         output[0] = 1;  
  7.         helper[len-1] = 1;  
  8.         for(int i=1;i<len;i++){  
  9.             output[i] = nums[i-1]*output[i-1];//计算i之前的乘积  
  10.             helper[len-i-1] = nums[len-i]*helper[len-i];//计算i之后的乘积  
  11.         }  
  12.         for(int i=0;i<len;i++){  
  13.             output[i] = output[i]*helper[i];  
  14.         }  
  15.         return output;  
  16.     }  
  17. }  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/47906303

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值