LeetCode 238. 除自身以外数组的乘积( Product of Array Except Self)

2023-05-13,,

题目描述

给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积

示例:

输入: [1,2,3,4]
输出: [24,12,8,6]

说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。

进阶:
你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)

解题思路

首先从后往前遍历一遍,用结果数组来存储除当前数外的后面所有数的乘积,然后从前往后遍历,用nums存储除当前数外前面的所有数乘积,再把与结果数组乘积相乘得到除当前数以外所有数的乘积。

代码

 class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> res(nums);
res[nums.size() - ] = ;
for(int i = res.size() - ; i >= ; i--)
res[i] = nums[i + ] * res[i + ];
for(int i = ; i < res.size(); i++){
res[i] *= nums[i - ];
nums[i] *= nums[i - ];
}
return res;
}
};

LeetCode 238. 除自身以外数组的乘积( Product of Array Except Self)的相关教程结束。

《LeetCode 238. 除自身以外数组的乘积( Product of Array Except Self).doc》

下载本文的Word格式文档,以方便收藏与打印。