自学内容网 自学内容网

leetcode-238. 除自身以外数组的乘积-前n项的思想

给你一个整数数组 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 <= 105
  • -30 <= nums[i] <= 30
  • 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在  32 位 整数范围内

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

class Solution {
public:
    /**
     * 计算除自身以外的数字乘积
     * @param nums 一个整数数组
     * @return 返回修改后的数组,其中每个元素是除自身以外所有元素的乘积
     */
    vector<int> productExceptSelf(vector<int>& nums) {
        // 获取数组的长度
        int len = nums.size();
        
        // 定义两个数组,sun用于存储从左到右的累积乘积,res用于存储从右到左的累积乘积
        // 由于C++没有提供像Python那样的动态数组,因此需要预先定义足够大的数组
        int sun[len+10];
        int res[len+10];
        
        // 初始化累积乘积的边界条件
        sun[0] = 1;
        res[len+1] = 1;
        
        // 从左到右计算累积乘积
        for(int i = 0; i < len; i++) {
            sun[i+1] = nums[i] * sun[i];
        }
        
        // 从右到左计算累积乘积
        for(int i = len-1; i >= 0; i--) {
            res[i+1] = nums[i] * res[i+2];
        }
      
        // 将两个方向的累积乘积结合起来,得到除自身以外的乘积
        for(int i = 0; i < len; i++) {
            if(i == 0) {
                nums[i] = res[2];
            } else if(i == len - 1) {
                nums[i] = sun[len-1];
            } else {
                nums[i] = sun[i] * res[i+2];
            }
        }
        
        // 返回计算后的数组
        return nums;
    }
};
       

 


原文地址:https://blog.csdn.net/weixin_57011178/article/details/142617792

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!