力扣面试150题打卡第五天
题目链接:238. 除自身以外数组的乘积 - 力扣(LeetCode)

一 题目概述:
该题目需要实现的是,返回一个数组(answer),这个数组 answer[i] 等于题目给出的数组 nums 中除 nums[i] 之外其余各元素的乘积 。(本题要求不能使用除法)
二实现思路
2.1错误想法
题目说不能用除法,实际上不说也不可用除法,可能有人会想先计算出所有数字的乘积,然后,在除于当前这个位置的数字即可,但是这个位置如果为0呢,这就回导致错误
2.2正确思路
另外设计两个数组,大小和nums一样大,Right[]和Left[],Rignt[]记录当前位置右侧的数字的乘积,Left[]记录当前位置左数字的乘积
两个遍历结束之后,求当前位置,除了当前位置所有数字的乘积,就变成了Right[],Left[],两个数组对应位置的乘积
时间复杂度和空间复杂度都是O(n)
三代码如下
class Solution {public int[] productExceptSelf(int[] nums) {int len = nums.length;int answer[] = new int[len];//构造两个数组,一个表示该位置右侧的所有数字的乘积//另一个表示该位置左侧所有数字的乘积int Right[] = new int [len];int Left[] = new int[len];//这里要做一个初始化,不要乘积全为0,同理Right也要做初始化Left[0] = 1;for(int i=1;i<len;i++){Left[i] = Left[i-1]*nums[i-1];}//同理初始化Right[len-1] = 1;for(int i=len-2;i>=0;i--){Right[i] = Right[i+1]*nums[i+1];}//将结果转化为两个数组对应位置的乘积for(int i=0;i<len;i++){answer[i] = Right[i]*Left[i];}return answer;}
}
四 优化
下面的优化可以将空间复杂度降到O(1)
代码如下
主要变化就是没有构造两个其他数组,用一个数字Right来代表该位置右侧的乘积
class Solution {public int[] productExceptSelf(int[] nums) {int len = nums.length;int answer[] = new int[len];answer[0]=1;for(int i=1;i<len;i++){answer[i] = answer[i-1]*nums[i-1];}//这里right代表了右侧数字的乘积int Right = 1;for(int i=len-1;i>=0;i--){answer[i] = answer[i]*Right;Right*=nums[i];}return answer;}
}
