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

  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) - 使用了两个额外数组。
相关推荐
karry_k10 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k10 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
vibecoding日记12 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr213814 小时前
Verilog参数化游程编码RLE模块
算法
SamDeepThinking14 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
望易14 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
她的男孩17 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
复杂网络18 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
荣码19 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python