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;
    }
};
相关推荐
yyjtx2 小时前
DHU上机打卡D26
数据结构·c++·算法
智者知已应修善业2 小时前
【蓝桥杯单词分析最多字母次数并列字典最小输出】2025-4-15
c语言·c++·经验分享·笔记·算法·蓝桥杯
ValhallaCoder6 小时前
hot100-栈
数据结构·python·算法·
WW_千谷山4_sch10 小时前
洛谷B3688:[语言月赛202212]旋转排列(新解法:deque双端队列)
数据结构·c++·算法
Zachery Pole10 小时前
【代码随想录】二叉树
算法
漂流瓶jz10 小时前
UVA-11214 守卫棋盘 题解答案代码 算法竞赛入门经典第二版
c++·算法·dfs·aoapc·算法竞赛入门经典·迭代加深搜索·八皇后
浮生091910 小时前
DHUOJ 基础 88 89 90
算法
v_for_van11 小时前
力扣刷题记录7(无算法背景,纯C语言)
c语言·算法·leetcode
先做个垃圾出来………11 小时前
3640. 三段式数组 II
数据结构·算法