当前位置:网站首页>【LeetCode】Day107-除自身以外数组的乘积
【LeetCode】Day107-除自身以外数组的乘积
2022-07-30 05:10:00 【倒过来是圈圈】
题目
题解
左右乘积列表
初始化两个空数组 L 和 R。对于给定索引 i,L[i] 代表的是 i 左侧所有数字的乘积,R[i] 代表的是 i 右侧所有数字的乘积。
class Solution {
public int[] productExceptSelf(int[] nums) {
int n=nums.length;
int[] L=new int[n];
int[] R=new int[n];
L[0]=1;
R[n-1]=1;
for(int i=1;i<n;i++){
L[i]=L[i-1]*nums[i-1];//nums[i]左边所有数的乘积
R[n-i-1]=R[n-i]*nums[n-i];//nums[i]右边所有数的乘积
}
int[] res=new int[n];
for(int i=0;i<n;i++){
res[i]=L[i]*R[i];//除nums[i]以外所有数的乘积
}
return res;
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n)
空间复杂度O(1)
由于输出数组不算在空间复杂度内,那么我们可以将 L 或 R 数组用输出数组来计算。
左侧所有数乘积用 res[] 存储,右侧所有数乘积用一个变量 R 存储,将空间复杂度降至O(1)
class Solution {
public int[] productExceptSelf(int[] nums) {
int n=nums.length;
int[] res=new int[n];
res[0]=1;
for(int i=1;i<n;i++){
res[i]=res[i-1]*nums[i-1];//nums[i]左边所有数的乘积
}
int R=1;//nums[i]右边所有数的乘积
for(int i=n-1;i>=0;i--){
res[i]=res[i]*R;
R=R*nums[i];
}
return res;
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( 1 ) O(1) O(1)
边栏推荐
猜你喜欢

七、自定义配置

1315_Use the LOOPBACK simulation mode to test whether the pyserial installation is successful

即刻报名|如何降低云上数据分析成本?

mysql cannot connect remotely Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060 "Unknown error")

小程序使用npm包定制全局样式

oracle触发器的自治事务

美国再次加息75个基点 陷入“技术性衰退”?加密市场却呈现复苏力量

GO language study notes one

ms project2010项目管理软件使用技巧总结

Seven, custom configuration
随机推荐
oracle触发器的自治事务
Simulation problem (below)
uni-app realizes cross-end development of mobile phone Bluetooth to receive and send data
RadonDB MySQL Kubernetes 2.2.0 发布!
ms project2010项目管理软件使用技巧总结
22. 为什么需要消息队列?使用消息队列有什么好处?
LeetCode Algorithm 2326. Spiral Matrix IV
NFT 产品设计路线图
Requirements design document and the changing role of the product manager
RadonDB MySQL on K8s 2.1.3 发布!
Dynamic Programming Problems (End)
解读 Kylin 3.0.0 | 更敏捷、更高效的 OLAP 引擎
Plan for many situations in the processing chain
容器化 | 在 K8s 上部署 RadonDB MySQL Operator 和集群
Us to raise interest rates by 75 basis points in "technical recession"?Encryption market is recovering
POJ1321 chessboard problem (detailed explanation)
Divide and conquer. L2-025
The Double Pointer Problem (Part 1)
Hexagon_V65_Programmers_Reference_Manual (12)
Nuxt3 learning