力扣 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—620. 有趣的电影&&Q3. 有趣的电影【简单】
数据库·后端·mysql·算法·leetcode·职场和发展
2301_800256111 小时前
地理空间数据库中的CPU 和 I/O 开销
数据库·算法·oracle
一个不知名程序员www2 小时前
算法学习入门---结构体和类(C++)
c++·算法
XFF不秃头4 小时前
力扣刷题笔记-旋转图像
c++·笔记·算法·leetcode
王老师青少年编程5 小时前
csp信奥赛C++标准模板库STL案例应用3
c++·算法·stl·csp·信奥赛·lower_bound·标准模版库
有为少年5 小时前
Welford 算法 | 优雅地计算海量数据的均值与方差
人工智能·深度学习·神经网络·学习·算法·机器学习·均值算法
Ven%6 小时前
从单轮问答到连贯对话:RAG多轮对话技术详解
人工智能·python·深度学习·神经网络·算法
山楂树の6 小时前
爬楼梯(动态规划)
算法·动态规划
谈笑也风生6 小时前
经典算法题型之复数乘法(二)
开发语言·python·算法