当前位置:网站首页>leetcode-238.除自身以外数组的乘积
leetcode-238.除自身以外数组的乘积
2022-07-25 09:08:00 【KGundam】
数学问题
题目详情
给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。
题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。
请不要使用除法,且在 O(n) 时间复杂度内完成此题。
示例1:
输入: nums = [1,2,3,4]
输出: [24,12,8,6]
示例2:
输入: nums = [-1,1,0,-3,3]
输出: [0,0,9,0,0]
思路:
像脑筋急转弯一样,数组中每个数除自身外其他数的乘积就是左边乘右边
而怎么获得左边/右边所有数的乘积呢?
类似动态规划,我们从左到右遍历一次,用left记忆遍历到的数nums[i]的左边乘积
即nums[0]*nums[1]...*nums[i-1]
将其和res[i]相乘之后更新left直到所有nums[i]都得到对应的res[i]
(此时一遍遍历得到了所有左边乘积)
然后用相同的方法从右到左遍历一次,利用right记忆,道理一样
最后两边遍历完即得到了所需要的结果
(注意初始化left和right都是1)
我的代码:
class Solution
{
public:
vector<int> productExceptSelf(vector<int>& nums)
{
int n = nums.size(), left = 1, right = 1;
vector<int> res(n, 1);
//左乘积
for (int i = 0; i < n; ++i)
{
res[i] *= left;
left *= nums[i];
}
//右乘积
for (int i = n-1; i >= 0; --i)
{
res[i] *= right;
right *= nums[i];
}
return res;
}
};
我们也可以将两个循环合并为一个,从而得到下面的代码:
class Solution
{
public:
vector<int> productExceptSelf(vector<int>& nums)
{
int n = nums.size();
int left = 1, right = 1;
vector<int> res(n, 1);
for (int i = 0; i < n; ++i)
{
res[i] *= left;
left *= nums[i];
res[n-1-i] *= right;
right *= nums[n-1-i];
}
return res;
}
};
边栏推荐
- 机器人跳跃问题
- Wechat sports ground reservation applet graduation project of applet completion works (1) development outline
- Comments on specific applications of camera
- JDBC的api全解
- Graduation project of wechat small program ordering system of small program completion works (7) Interim inspection report
- 图解LeetCode——919. 完全二叉树插入器(难度:中等)
- Solutions to ten questions of leetcode database
- (self drawn ugly picture) simple understanding tcp/ip three handshakes and four waves
- 51 MCU internal peripherals: timer and counter
- This is the worst controller layer code I've ever seen
猜你喜欢
随机推荐
学习周刊-总第 63 期-一款开源的本地代码片段管理工具
Unity ugui interaction (new ideas)
Redis learning notes
Graduation design of wechat small program ordering system of small program completion works (5) assignment
【sklearn】sklearn.preprocessing.LabelEncoder
51 MCU internal peripherals: timer and counter
[hero planet July training leetcode problem solving daily] 19th binary tree
[STL]stack&queue模拟实现
Illustration leetcode - 1184. Distance between bus stops (difficulty: simple)
Cool canvas animation shock wave JS special effect
Collection of common algorithm questions in test post interview
51单片机内部外设:定时器和计数器
IDEA下依赖冲突解决方法
51单片机外设篇:蜂鸣器
超赞的yolo目标检测训练所用垃圾分类数据集共享——标注好的约3000张
Wechat reservation applet graduation project (7) mid term inspection report of applet completion works
uniapp中scroll-view的坑
Labview--- signal generator
优炫数据库对数据的加密是如何做的?
unity客户端读取文本配置




![[hero planet July training leetcode problem solving daily] 19th binary tree](/img/16/d4beab998f00e09bb45c64673bb2c8.png)




