力扣 238. 除自身以外数组的乘积

🔗 https://leetcode.cn/problems/product-of-array-except-self

题目

  • 给定一个数组,返回除了当前元素,其余所有元素的乘积
  • 不能用除法,所有数字的乘积都在 int 32 位之内

思路

  • solution 1
    • presum 的思路变成 prefix_product 和 suffix_product 的计算,当前元素的答案,就是对应的 prefix_product 和 suffix_product 的乘积
  • solution 2
    • 进阶要求仅用额外的 O(1) 空间,那遍顺序遍历一遍,逆序遍历一遍,记录对应的乘积,更新当前元素的答案

代码

cpp 复制代码
class Solution {
public:
    vector<int> solution1(vector<int>& nums) {
        int n = nums.size();
        vector<int> suffix_product(n+1), prefix_product(n+1);
        suffix_product[n] = prefix_product[0] = 1; 
        for (int i = 0; i < nums.size(); i++) {
            prefix_product[i + 1] = prefix_product[i] * nums[i];
            suffix_product[n - i -1] = suffix_product[n - i] * nums[n - i -1];
        }
        vector<int> ans(n);
        for (int i = 0; i < n; i++) {
            ans[i] = prefix_product[i] * suffix_product[i+1];
        }
        return ans; 
    }

    vector<int> solution2(vector<int>& nums) {
        int n = nums.size();
        vector<int> ans(n, 1);
        int pre_prod = 1;
        for (int i = 0; i < n; i++) {
            ans[i] = pre_prod;
            pre_prod *= nums[i];
        }
        int suf_prod = 1;
        for (int i = n - 1; i >= 0; i--) {
            ans[i] *= suf_prod;
            suf_prod *= nums[i];
        }
        return ans;
    }

    vector<int> productExceptSelf(vector<int>& nums) {
        //return solution1(nums);
        return solution2(nums);
        
    }
};
相关推荐
我想吃烤肉肉1 分钟前
leetcode-sql数据库面试题冲刺(高频SQL五十题)
数据库·sql·leetcode
小六子成长记2 小时前
C语言数据结构之顺序表
数据结构·链表
北顾南栀倾寒2 小时前
[算法笔记]cin和getline的并用、如何区分两个数据对、C++中std::tuple类
笔记·算法
一只大侠3 小时前
牛客周赛A:84:JAVA
算法
豆豆酱3 小时前
Informer方法论详解
算法
槐月初叁4 小时前
多模态推荐系统指标总结
算法
迪小莫学AI4 小时前
LeetCode 2588: 统计美丽子数组数目
算法·leetcode·职场和发展
昂子的博客4 小时前
热门面试题第十天|Leetcode150. 逆波兰表达式求值 239. 滑动窗口最大值 347.前 K 个高频元素
算法
卑微小文5 小时前
2025国内网络反爬新高度:代理IP智能轮换算法揭秘
后端·算法·架构
ChinaRainbowSea5 小时前
MySQL 索引的数据结构(详细说明)
java·数据结构·数据库·后端·mysql