Leetcode_C++之238. Product of Array Except Self(除本身元素之外数组其他元素的积)

该博客讨论了一道编程题,要求在O(n)时间复杂度内且不使用除法计算数组中每个元素去除自身后的乘积。作者提出了两种解决方案,通过空间优化避免了额外数组的使用,实现了空间复杂度为O(1)。通过左右两个向中间遍历的过程,分别计算出数组元素左边和右边的乘积,然后结合这两个结果得到最终答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目名称

  1. Product of Array Except Self

题目描述

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]

Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Constraints:
2 <= nums.length <= 105
-30 <= nums[i] <= 30
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Follow up:
Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

初试思路

1、空间换时间,用数组代替一层for循环。
2、重复利用数组空间,避免额外数组,见注释。

初试代码

// 我的代码1
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        // res[i] = num[0]*...*nums[i-1]*  1  *nums[i+1]*.. *nums[nums.size()-1]
        vector<int> rights(nums.size());
        vector<int> results(nums.size());
        rights[nums.size()-1] = 1;
        for(int i=nums.size()-1; i>0; i--){
            rights[i-1] = rights[i] * nums[i];
        }
        int left = 1;
        for(int i=0; i<nums.size(); i++){
            results[i] = left * rights[i];
            left = left * nums[i];
        }
        return results;
    }
};
// 我的代码2
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        // res[i] = num[0]*...*nums[i-1]*  1  *nums[i+1]*.. *nums[nums.size()-1]
        //vector<int> rights(nums.size());
        vector<int> results(nums.size());
        results[nums.size()-1] = 1; //重复利用results来存放rights
        for(int i=nums.size()-1; i>0; i--){
            results[i-1] = results[i] * nums[i];
        }
        int left = 1;
        for(int i=0; i<nums.size(); i++){
            results[i] = left * results[i]; // results[i+1]实际上还是之前算的rights[i+1]的值
            left = left * nums[i];
        }

        return results;

    }
};

学到了啥

1、问题拆解:左*右;
2、空间换时间;
3、若额外数组的元素都会只用到一次,则可以用省去该额外数组。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值