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

  1. 思路分析
    • 对每个 nums[i],计算其左边所有元素的乘积和右边所有元素的乘积,然后将这两个乘积相乘,就得到了除 nums[i] 之外其余各元素的乘积。
    • 例如对于数组 [a, b, c, d],计算 nums[1](即 b)的结果时,左边元素乘积为 a,右边元素乘积为 c * d,那么结果就是 a * c * d
  2. 算法思路
    • 初始化:创建数组LProduct和RProduct。
    • 计算左边乘积
      • 左乘积数组 lProduct[i]:存储索引 i 左边所有元素的乘积。
    • 计算右边乘积并合并结果
      • 右乘积数组 rProduct[i]:存储索引 i 右边所有元素的乘积。
    • 结果数组 :
      • 结果数组 res[i] = lProduct[i] * rProduct[i]。
  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) - 使用了两个额外数组。
相关推荐
二哈赛车手6 小时前
新人笔记---ApiFox的一些常见使用出错
java·笔记·spring
吃好睡好便好6 小时前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
栗子~~6 小时前
JAVA - 二层缓存设计(本地缓冲+redis缓冲+广播所有本地缓冲失效) demo
java·redis·缓存
YDS8296 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— RAG知识库的搭建和接口实现
java·ai·springboot·agent·rag·deepseek
仰泳之鹅7 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
未若君雅裁8 小时前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis
AI人工智能+电脑小能手8 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm
阿维的博客日记9 小时前
Nacos 为什么能让配置动态生效?(涉及 @RefreshScope 注解)
java·spring
雨辰AI9 小时前
SpringBoot3 + 人大金仓读写分离 + 分库分表 + 集群高可用 全栈实战
java·数据库·mysql·政务
x_yeyue9 小时前
三角形数
笔记·算法·数论·组合数学