当前位置:网站首页>【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)
边栏推荐
- RadonDB MySQL Kubernetes 2.2.0 发布!
- mysql isolation level
- 给小白的 PG 容器化部署教程(下)
- C# One Week Introductory "C# - Classes and Objects" Day Six
- Simulation problem (middle)
- Protobuf compound data types, speaking, reading and writing
- gnss rtcm rtklib Ntrip...
- Kyligence 亮相第五届南方信息大会并获评“CIO 优选数字化服务商”
- L2-025 分而治之
- Compound Types--references, pointers
猜你喜欢

Xiamen SenseCore Technology MC3172(1): Introduction and Environment Construction

Unity踩坑记录 —— GetComponent的使用

Summary of skills in using ms project2010 project management software

1315_使用LOOPBACK模拟模式pyserial安装是否成功的测试
![[3D Detection Series-PointRCNN] Reproduces the PointRCNN code, and realizes the visualization of PointRCNN3D target detection, including the download link of pre-training weights (starting from 0 and](/img/ca/17c047b8b1f030cc4ebb7e354070d9.png)
[3D Detection Series-PointRCNN] Reproduces the PointRCNN code, and realizes the visualization of PointRCNN3D target detection, including the download link of pre-training weights (starting from 0 and

Code readability, pre-checks, comments and summaries

Simulation problem (middle)

L2-025 分而治之

pycharm上的tensorflow环境搭载

QT(39)-vs development qt program prompts that the source file cannot be opened
随机推荐
Us to raise interest rates by 75 basis points in "technical recession"?Encryption market is recovering
RadonDB MySQL on K8s 2.1.4 发布!
双指针问题(下)
std::vector中保存指针时用法
gnss rtcm rtklib Ntrip...
光明区关于促进科技创新的若干措施(征求意见稿)
Alibaba Cloud's EasyNLP Chinese text image generation model takes you to become an artist in seconds
斐波那契数列的递归优化《备忘录递归》
Whole process scheduling - Azkaban entry and advanced
翻译 | Kubernetes 将改变数据库的管理方式
GO语言学习笔记一
双指针问题(上)
Recursive Optimization of Fibonacci Sequences "Memo Recursion"
C语言中的基本库函数(qsort)
七、自定义配置
Record of problems encountered by the pyinstaller packager
Learning of redis_Basic part
动态规划问题(完结篇)
WPF study notes "WPF Layout Basics"
el-table中加入el-input框和el-input-number框,实现el-table的可编辑功能