LeetCode热题100 除了自身以外数组的乘积

题目描述

给你一个整数数组 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]

提示:

2<=nums.length<=1052 <= nums.length <= 10^52<=nums.length<=105
−30<=nums[i]<=30-30 <= nums[i] <= 30−30<=nums[i]<=30

输入 保证 数组 answer[i] 在 32 位 整数范围内

思路1

计算左边的前缀和和右边的前缀和,直接相乘即可。

代码1

cpp 复制代码
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
    	// 初始化前后缀 
    	int n = nums.size();
        vector<int>pre(n, 0);
        vector<int>suf(n, 0);
        pre[0] = 1;
		for(int i = 1; i < n; ++i)
		{
			pre[i] = pre[i - 1] * nums[i - 1];
		}        
		suf.back() = 1;
		for(int i = n - 2; i >= 0; --i)
		{
			suf[i] = suf[i + 1] * nums[i + 1];
		}        
		
		// 输出答案
		vector<int> ans;
		for(int i = 0 ; i < n; ++i) 
		{
			ans.push_back(pre[i] * suf[i]);
		}
		return ans;
    }
};

思路2

在思路1的基础上,省略前后缀的空间,直接用ans数组作为前缀,然后倒置计算后缀的同时得出答案。

代码2

cpp 复制代码
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
		int n = nums.size();
		vector<int>ans(n, 1);
		for(int i = 1; i < n; ++i)
		{
			ans[i] = nums[i - 1] * ans[i - 1];
		} 
		int suf = 1; // 代表后缀 
		for(int i = n - 1; i >=0; --i)
		{
			ans[i] = ans[i] * suf;
			suf *= nums[i];
		}
		return ans;
    }
};
相关推荐
故事和你912 分钟前
蓝桥杯-2025年C++B组国赛
开发语言·软件测试·数据结构·c++·算法·职场和发展·蓝桥杯
py有趣8 分钟前
力扣热门100题之合并区间
算法·leetcode
派大星~课堂10 分钟前
【力扣-138. 随机链表的复制 ✨】Python笔记
python·leetcode·链表
cpp_250115 分钟前
P10108 [GESP202312 六级] 闯关游戏
数据结构·c++·算法·动态规划·题解·洛谷·gesp六级
Lzh编程小栈19 分钟前
数据结构与算法之队列深度解析:循环队列+C 语言硬核实现 + 面试考点全梳理
c语言·开发语言·汇编·数据结构·后端·算法·面试
AbandonForce21 分钟前
模拟实现vector
开发语言·c++·算法
少许极端26 分钟前
算法奇妙屋(四十二)-贪心算法学习之路 9
学习·算法·贪心算法
CoderCodingNo26 分钟前
【NOIP】1998真题解析 luogu-P1010 幂次方 | GESP四、五级以上可练习
算法
py有趣33 分钟前
力扣热门100题之最小覆盖子串
算法·leetcode
汀、人工智能35 分钟前
[特殊字符] 第102课:添加与搜索单词
数据结构·算法·均值算法·前缀树·trie·添加与搜索单词