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)

相关推荐
田里的水稻4 分钟前
FA_建图和定位(ML)-超宽带(UWB)定位
人工智能·算法·数学建模·机器人·自动驾驶
Navigator_Z6 分钟前
LeetCode //C - 964. Least Operators to Express Number
c语言·算法·leetcode
郝学胜-神的一滴7 分钟前
Effective Modern C++ 条款40:深入理解 Atomic 与 Volatile 的多线程语义
开发语言·c++·学习·算法·设计模式·架构
摸鱼仙人~12 分钟前
算法题避坑指南:数组/循环范围的 `+1` 到底什么时候加?
算法
liliangcsdn18 分钟前
基于似然比的显著图可解释性方法的探索
人工智能·算法·机器学习
骇城迷影20 分钟前
代码随想录:二叉树篇(中)
数据结构·c++·算法·leetcode
期末考复习中,蓝桥杯都没时间学了34 分钟前
力扣刷题23
算法·leetcode·职场和发展
菜鸡儿齐36 分钟前
leetcode-子集
算法·leetcode·深度优先
今儿敲了吗39 分钟前
28| A-B数对
数据结构·c++·笔记·学习·算法
Desirediscipline42 分钟前
#include<limits>#include <string>#include <sstream>#include <iomanip>
java·开发语言·前端·javascript·算法