当前位置:网站首页>【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)
边栏推荐
- go语言学习笔记四
- Kyligence 亮相第五届南方信息大会并获评“CIO 优选数字化服务商”
- WPF introduces ttf icon file usage record
- pycharm上的tensorflow环境搭载
- mysql cannot connect remotely Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060 "Unknown error")
- RadonDB MySQL on K8s 2.1.2 发布!
- Unity3D Application simulation enters the front and background and pauses
- Hexagon_V65_Programmers_Reference_Manual(10)
- Three Solutions for SaaS Multi-tenant Data Isolation
- GO语言学习笔记一
猜你喜欢

斐波那契数列的递归优化《备忘录递归》

Simulation problem (middle)
![[High Performance Computing] openMP](/img/a5/2cfd760a26edb379d337eb3d1605d5.jpg)
[High Performance Computing] openMP

Acwing完全数

Hexagon_V65_Programmers_Reference_Manual(10)

Discourse Custom Header Links

Small program npm package--API Promise

mysql隔离级别

给小白的 PostgreSQL 容器化部署教程(上)

Using the GPU parallel computing 】 【 OpenCL&OpenCLUtilty GPU parallel computing
随机推荐
GO language study notes one
go语言学习笔记四
C语言实现安全性极高的游戏存档并读档
Small program npm package--API Promise
pycharm上的tensorflow环境搭载
涂鸦Wi-Fi&BLE SoC开发幻彩灯带
Small programs use npm packages to customize global styles
go language study notes 4
handler+message [message mechanism]
Kyligence 入选 Gartner 2022 数据管理技术成熟度曲线报告
Hexagon_V65_Programmers_Reference_Manual(11)
C. Qualification Rounds
pytorch官网中如何选择以及后面的安装和pycharm测试步骤
RadonDB MySQL on K8s 2.1.3 发布!
小程序使用npm包定制全局样式
Seven, custom configuration
LeetCode Algorithm 328. Parity linked list
Us to raise interest rates by 75 basis points in "technical recession"?Encryption market is recovering
Simulation problem (below)
Code readability, pre-checks, comments and summaries