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

题目描述

给你一个整数数组 nums,返回 数组 answer ,其中 answeri 等于 nums 中除了 numsi 之外其余各元素的乘积 。

题目数据 保证 数组 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<=numsi<=30-30 <= numsi <= 30−30<=numsi<=30

输入 保证 数组 answeri 在 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;
    }
};
相关推荐
不会就选b9 小时前
算法日常・每日刷题--<贪心>14
算法
mmmmath_311 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z11 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧12 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背13 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝13 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
参.商.13 小时前
【Day 53】76. 最小覆盖子串
leetcode·golang
HZZD_HZZD13 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法
shirsl15 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法