力扣:除自身以外数组的乘积

  1. 思路分析
    • 对每个 nums[i],计算其左边所有元素的乘积和右边所有元素的乘积,然后将这两个乘积相乘,就得到了除 nums[i] 之外其余各元素的乘积。
    • 例如对于数组 [a, b, c, d],计算 nums[1](即 b)的结果时,左边元素乘积为 a,右边元素乘积为 c * d,那么结果就是 a * c * d
  2. 算法思路
    • 初始化:创建数组LProduct和RProduct。
    • 计算左边乘积
      • 左乘积数组 lProducti:存储索引 i 左边所有元素的乘积。
    • 计算右边乘积并合并结果
      • 右乘积数组 rProducti:存储索引 i 右边所有元素的乘积。
    • 结果数组 :
      • 结果数组 resi = lProducti * rProducti
  3. 代码实现:
java 复制代码
package main.leetcode75.arr_str;

import java.util.Arrays;

/**
 * @ClassName ProductExceptSelf
 * @Description
 * @Author Feng
 * @Date 2025/12/29
 **/
public class ProductExceptSelf {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        int[] lProduct = new int[nums.length];
        int[] rProduct = new int[nums.length];

        // 初始化lproduct数组的值
        lProduct[0] = 1;
        for (int i = 1; i < nums.length; i++) {
            lProduct[i] = nums[i - 1] * lProduct[i - 1];
        }

        rProduct[rProduct.length-1] = 1;
        for (int i = rProduct.length-2; i >= 0 ; i--) {
            rProduct[i] = nums[i+1] * rProduct[i+1];
        }

        for (int i = 0; i < nums.length; i++) {
            res[i] = lProduct[i] * rProduct[i];
        }

        return res;
    }

    public static void main(String[] args) {
        ProductExceptSelf productExceptSelf = new ProductExceptSelf();
        int[] nums = {1, 2, 3, 4};
        int[] result = productExceptSelf.productExceptSelf(nums);
        Arrays.stream(result).forEach(System.out::println);
    }
}
  1. 复杂度分析
    • 时间复杂度:O(n) - 三次遍历数组。
    • 空间复杂度:O(n) - 使用了两个额外数组。
相关推荐
摇滚侠9 分钟前
Java 全栈开发实战教程 课程笔记 34-36
java·笔记
芝士熊爱编程14 分钟前
创建型模式-单例模式
java·单例模式·设计模式
大模型码小白18 分钟前
Spring AI 框架实战:Java 后端集成大模型的架构设计与工程落地
java·人工智能·python·spring
闪电悠米1 小时前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
weixin_BYSJ19871 小时前
「课设设计」springboot校园超市助购系统26449 (附源码)
java·javascript·spring boot·python·django·flask·php
栋***t1 小时前
从“纸质试卷”到“AI智能组卷”,麦塔在线考试系统如何重构出题逻辑?
java·大数据·人工智能·算法·重构
wabs6661 小时前
关于图论【卡码网100.最大岛屿的面积的思考】
数据结构·算法·图论
CHANG_THE_WORLD1 小时前
深入理解递归:从函数调用到调用栈的完整执行过程
java·开发语言·算法
xexpertS1 小时前
CI/CD 熔断机制:如何通过编排级熔断器提升开发者效率
java·linux·运维
zy happy2 小时前
VMware虚拟机添加新的硬盘
java·linux·jvm·docker