LeetCode(13)除自身以外数组的乘积【数组/字符串】【中等】

目录

链接: 238. 除自身以外数组的乘积

1.题目

给你一个整数数组 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 <= 10^5
  • -30 <= nums[i] <= 30
  • 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内

**进阶:**你可以在 O(1) 的额外空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组 不被视为 额外空间。)


2.答案

java 复制代码
class Solution {
    public int[] productExceptSelf(int[] nums) {
        if (nums.length < 2) {
            return nums;
        }
        // 获取前面部分乘积
        int beforeAll = 1;
        int[] before = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            if (i != 0) {
                beforeAll = beforeAll * nums[i - 1];
            }
            before[i] = beforeAll;
        }
        // 获取后面部分乘积
        int afterAll = 1;
        int[] after = new int[nums.length];
        for (int i = nums.length - 1; i >= 0; i--) {
            if (i != nums.length - 1) {
                afterAll = afterAll * nums[i + 1];
            }
            after[i] = afterAll;
        }
        // 计算结果
        int[] answer = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            answer[i] = before[i] * after[i];
        }
        return answer;
    }
}

3.提交结果截图

整理完毕,完结撒花~ 🌻

相关推荐
深邃-1 小时前
【数据结构与算法】-二叉树(2):实现顺序结构二叉树(堆的实现),向上调整算法,向下调整算法,堆排序,TOP-K问题
数据结构·算法·二叉树·排序算法·堆排序··top-k
We་ct4 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
王老师青少年编程8 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
叼烟扛炮8 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
天疆说9 小时前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习
wuweijianlove9 小时前
关于算法设计中的代价函数优化与约束求解的技术7
算法
小程故事多_809 小时前
[大模型面试系列] 多轮对话 Agent 设计实战(含窗口优化 + 工具调用精髓)
人工智能·面试·职场和发展
leoufung10 小时前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了10 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
HXDGCL10 小时前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化