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

原题链接:. - 力扣(LeetCode)

给你一个整数数组 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 位 整数范围内

思路:

本题可采用 取每个元素 nums[ i ]之前所有的元素 的乘积 pre[ i ]和 每个元素之后所有元素的乘积 behind[ i ] 做乘积的方法,得出 res[ i ]。即 res[ i ] = pre[ i ] * behind[ i ],具体可见网上大佬的解析:

代码:

java 复制代码
class Solution {
    public int[] productExceptSelf(int[] nums) {    
        int n=nums.length;
        int[] pre= new int[n];
        int[] behind= new int[n];
        int[] res= new int[n];
        pre[0]=1;
        for(int i=1;i<n;i++){
            pre[i]=pre[i-1]*nums[i-1];
        }
        behind[n-1]=1;
        for(int i=n-2;i>=0;i--){
            behind[i]=behind[i+1]*nums[i+1];
        }
        
        for(int i=0;i<n;i++){
            res[i]=pre[i]*behind[i];
        }
        return res;
    }
}

参考:. - 力扣(LeetCode)

相关推荐
MobotStone1 小时前
从金鱼记忆到过目不忘:Transformer 如何让AI真正理解一句话?
算法
炽烈小老头2 小时前
【每天学习一点算法 2025/12/19】二叉树的层序遍历
数据结构·学习·算法
Xの哲學2 小时前
Linux grep命令:文本搜索的艺术与科学
linux·服务器·算法·架构·边缘计算
soft20015252 小时前
MySQL Buffer Pool深度解析:LRU算法的完美与缺陷
数据库·mysql·算法
WBluuue3 小时前
AtCoder Beginner Contest 436(ABCDEF)
c++·算法
fie88893 小时前
广义 S 变换(GST)地震信号时频谱
算法
json{shen:"jing"}4 小时前
1-C语言的数据类型
c语言·c++·算法
im_AMBER4 小时前
数据结构 13 图 | 哈希表 | 树
数据结构·笔记·学习·算法·散列表
LYFlied4 小时前
【算法解题模板】动态规划:从暴力递归到优雅状态转移的进阶之路
数据结构·算法·leetcode·面试·动态规划
Hcoco_me5 小时前
RTMPose_JSON相关解读
算法·数据挖掘·json·聚类