力扣 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);
        
    }
};
相关推荐
茉莉玫瑰花茶2 分钟前
C++ 17 详细特性解析(5)
开发语言·c++·算法
cpp_250114 分钟前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_250121 分钟前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
uesowys30 分钟前
Apache Spark算法开发指导-Factorization machines classifier
人工智能·算法
TracyCoder1231 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
季明洵1 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
shandianchengzi1 小时前
【小白向】错位排列|图文解释公考常见题目错位排列的递推式Dn=(n-1)(Dn-2+Dn-1)推导方式
笔记·算法·公考·递推·排列·考公
I_LPL1 小时前
day26 代码随想录算法训练营 回溯专题5
算法·回溯·hot100·求职面试·n皇后·解数独
Yeats_Liao1 小时前
评估体系构建:基于自动化指标与人工打分的双重验证
运维·人工智能·深度学习·算法·机器学习·自动化
only-qi1 小时前
leetcode19. 删除链表的倒数第N个节点
数据结构·链表