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)

相关推荐
嵌入式 Linux手记4 分钟前
嵌入式面试都考的置位清位:位运算四件套
linux·c语言·驱动开发·面试·职场和发展·嵌入式
漂流瓶jz5 分钟前
UVA-1615 高速公路 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·贪心算法·贪心·aoapc·算法竞赛入门经典·uva
凌冰_10 小时前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi11 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
戴·菲瑜11 小时前
为什么PPO难以做出顶级棋类引擎
算法·博弈论·rl·ppo
在所不辞兄13 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
文丑颜不良啊17 小时前
LeetCode3401~3420题目解析
java·leetcode
AvocadoZeroOneOI18 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊18 小时前
LeetCode3421~3440题目解析
java·leetcode
cjz389920 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法